简体   繁体   English

使用.Net将SQL导出到CSV文件

[英]SQL export to CSV file using .Net

I have an app that saves a sql data set to a csv file. 我有一个将sql数据集保存到csv文件的应用程序。 I read the data, loop each row saving into a string and then I save the string into a text file. 我读取数据,将每一行循环保存为字符串,然后将字符串保存为文本文件。 The problem is there is a over 25k rows and it takes a long time to process. 问题是行数超过25k,处理时间很长。 Is there a faster way to do this? 有更快的方法吗?

SqlDataAdapter sSQL2 = new SqlDataAdapter("SelUsersEmails", Conn);
DataSet RS2 = new DataSet();
sSQL2.Fill(RS2, "SelUsersEmails");


s = "UserID,SignUpDate,Email,PayPalEmail,Firstname,Lastname" + Environment.NewLine;



foreach (DataRow u in RS2.Tables["SelUsersEmails"].Rows)
{//loop each
        s += u["UserID"].ToString() + "," + u["SignUpDate"].ToString() + "," +["Email"].ToString() + "," + u["NetworkEmail"].ToString() + "," + ["Firstname"].ToString() + "," + u["Lastname"].ToString();

        s += Environment.NewLine;

}

There are many things that can be done - instead of string concatenation you can use StringBuilder to create it more efficiently. 有很多事情可以做-除了字符串连接,您还可以使用StringBuilder来更有效地创建它。

Another option it to stream the data to the file as you go along - this is the most memory efficient way, though can be more IO intensive. 另一个选择是将数据流传输到文件中-这是内存效率最高的方法,尽管可能会占用更多的IO。

But I suggest using FileHelpers to create the CSV file. 但是我建议使用FileHelpers创建CSV文件。 It is a popular library that is guaranteed to implement CSV properly (for example - what happens with your code if a field contains a comma?). 这是一个受欢迎的库,可以保证正确实现CSV(例如-如果字段包含逗号,您的代码会怎样?)。

Why don't you open the file ready for writing and write each line as you're looping through the resultset? 为什么不打开准备好写入的文件,并在遍历结果集时写每一行?

That's the most efficient way of creating the CSV file. 这是创建CSV文件的最有效方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM