Export SQL Server Data into CSV file

前端 未结 1 936
梦如初夏
梦如初夏 2020-12-18 16:47

I am trying to export data into a csv file from sql server. I have looked for help online and other support forums, but I can\'t find out how to do this? I have written my o

相关标签:
1条回答
  • 2020-12-18 17:39

    For what it's worth, if all you want is to take a query and dump the contents somewhere, it looks like you're doing a bit more work than you have to. The complexity may add to the challenge in debugging.

    A really bare bones example of reading a query and directing output to a file might look like this:

    SqlConnection sqlCon = new SqlConnection("REMOVED");
    sqlCon.Open(); 
    
    SqlCommand sqlCmd = new SqlCommand(
        "Select * from products.products", sqlCon);
    SqlDataReader reader = sqlCmd.ExecuteReader();
    
    string fileName = "test.csv";
    StreamWriter sw = new StreamWriter(fileName);
    object[] output = new object[reader.FieldCount];
    
    for (int i = 0; i < reader.FieldCount; i++)
        output[i] = reader.GetName(i);
    
    sw.WriteLine(string.Join(",", output));
    
    while (reader.Read())
    {
        reader.GetValues(output);
        sw.WriteLine(string.Join(",", output));
    }
    
    sw.Close();
    reader.Close();
    sqlCon.Close();
    

    While it may not look dramatically shorter than the code you listed, I do think it's simpler and will be easier to debug, out of the box. I haven't tested this, so I can't say for certain it works, although I would think it's pretty close.

    Another thing worth mentioning... neither of these is true CSV output. You need to be sure you handle embedded commas, return characters, etc, should they be in any of the output. That's easy enough to do, though.

    0 讨论(0)
提交回复
热议问题