我对 C# 中的循环 DataTable 有疑问
我有一个 DataTable 大约有 20.000 行和 60 列
我想写一个SQL查询来将DataTable中的所有数据插入数据库
我正在使用 My Sql
这是我的 SQL 语法:
"Insert into a values (...), (...), (...), ..."
"(...)"是一行中的所有数据
这是C#代码:
DataTable myDataTable; // myDataTable has 20.000 rows and 60 columns
string mySql = "insert into a values "
for(int iRow = 0; iRow < myDataTable.Rows.Count; iRow++)
{
mySql += "(";
for(int iColumn = 0; iColumn < myDataTable.Columns.Count; iColumn++)
{
string value = myDataTable.Rows[iRow][iColumn].ToString()
string parameter = "@" + iRows.ToString() + iColumns.ToString();
// here is some code for add "parameter" and "value" to MySqlCommand
mySql += ","
}
// remove "," at the end of string mySql
mySql = mySql.SubString(0, mySql.Length - 1);
mySql += "),"
}
// remove "," at the end of string mySql
// after that, I will execute mySql command to insert data into database here
当我运行该代码时,它需要很长时间才能完成
我尝试将“string”更改为“StringBuilder”,但它只是快了一点。
如何让代码运行得更快?
感谢大家的支持。
最佳答案
我在评论中要求提供一些时间信息,但随后我注意到了这行代码:
mySql = mySql.SubString(0, mySql.Length - 1);
我建议将其从您的循环中删除,并使用稍微更智能的代码来仅在需要时附加逗号。
例如,在内部循环中,将逗号添加到 mySql
变量之前而不是之后,但 iColumn == 0
除外。这将阻止不必要的逗号每次出现在字符串的末尾。
关于c# - 数据表循环性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15194504/