早在一天,我们使用GetRows的(),通过它拉回来一个数组和循环,因为它比使用rs.MoveNext通过记录走得更快。我正在编写一个应用程序,将50万行撤回并写入文件。从SQL中提取数据大约需要3分钟,但将其写入CSV需要12分钟。从它的外观来看,这是因为我正在循环访问一个SqlDataReader。什么是更快的选择?替代记录使用ADO循环
请记住,我不知道SQL结构将是什么样子,因为这是哪位告诉我的应用程序应该叫什么查询报表中。我看着使用linq并返回一个数组,但这需要知道结构,所以这是行不通的。
注意下面的代码,case语句有很多情况下,但以削减空间,我删除了所有这些,只有一个除外。
StringBuilder rowValue = new StringBuilder();
SqlDataReader reader = queryData.Execute(System.Data.CommandType.Text, sql, null);
//this is to handle multiple record sets
while (reader.HasRows)
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (rowValue.Length > 0)
rowValue.Append("\",\"");
else
rowValue.Append("\"");
rowValue.Append(reader.GetName(i).Replace("\"", "'").Trim());
}
rowValue.Append("\"" + Environment.NewLine);
File.AppendAllText(soureFile, rowValue.ToString());
while (reader.Read())
{
rowValue = new StringBuilder();
for (int i = 0; i < reader.FieldCount; i++)
{
String value = "";
switch (reader.GetFieldType(i).Name.ToLower())
{
case "int16":
value = reader.IsDBNull(i) ? "NULL" : reader.GetInt16(i).ToString();
break;
}
if (rowValue.Length > 0)
rowValue.Append("\",=\""); //seperate items
else
rowValue.Append("\""); //first item of the row.
rowValue.Append(value.Replace("\"", "'").Trim());
}
rowValue.Append("\"" + Environment.NewLine); //last item of the row.
File.AppendAllText(soureFile, rowValue.ToString());
}
//next record set
reader.NextResult();
if (reader.HasRows)
File.AppendAllText(soureFile, Environment.NewLine);
}
reader.Close();
如果您假设其他12分钟来自SqlDataReader,您如何知道将数据拉回3分钟?你如何分别测量这两件事? – RBarryYoung 2013-03-04 21:59:41
我不知道它是太慢还是尽可能快。这取决于写入文件的数据量以及您正在使用的硬盘驱动器(普通或SSD)的类型以及数据库是本地还是远程服务器等。但无论如何,代码示例可能会传播一些光线,可能会显示一些改进。 – Casperah 2013-03-04 21:59:42
也可以使用[bcp实用程序](http://msdn.microsoft.com/zh-cn/library/ms162802.aspx)直接将其导出到csv:http://dba.stackexchange.com/questions/23566/ write-select-result-to-a-csv-file – 2013-03-04 22:03:34