C# SQLServer retrieving results and place in a .csv format

前端 未结 5 648
孤街浪徒
孤街浪徒 2020-12-09 20:53

I had a look on the site and on Google, but I couldn\'t seem to find a good solution to what I\'m trying to do.

Basically, I have a client server application (C#) wh

5条回答
  •  北海茫月
    2020-12-09 21:09

    You can get the table column names like this:

    SqlConnection conn = new SqlConnection(connString);
    conn.Open();
    
    SqlCommand cmd = new SqlCommand(sql, conn);
    SqlDataReader rdr = cmd.ExecuteReader();
    
    DataTable schema = rdr.GetSchemaTable();
    foreach (DataRow row in schema.Rows) 
    {
        foreach (DataColumn col in schema.Columns)
            Console.WriteLine(col.ColumnName + " = " + row[col]);
    }
    
    rdr.Close()
    conn.Close();
    

    Of course you can determine the columns names with the first row only, here it does it on every rows.

    You can now put your own code to join the columns into a CSV line pretty easily...

    Thanks

提交回复
热议问题