数据表回路性能
问题描述:
我有一个关于循环DataTable的问题在C#数据表回路性能
我有一个DataTable拥有约20.000行和60列
我想写一个SQL查询中插入的所有数据在数据表数据库
我用我的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
当我运行的代码,它是花大量的时间来完成
我尝试从“字符串”更改为“StringBuilder”,但它稍快一点。
如何让代码更快运行?
感谢您的支持。
答
我要求在评论一些定时信息,但后来我发现这行代码:
mySql = mySql.SubString(0, mySql.Length - 1);
我建议删除,从你的循环,并有轻微聪明的代码只添加逗号时需要。
例如,在内循环中,在每个参数之前而不是之后添加逗号到mySql
变量,除了其中iColumn == 0
。这样可以避免每次在字符串末尾出现不必要的逗号。
+0
感谢您的支持。 – n2h 2013-03-04 05:54:25
什么是*这里是一些代码添加“参数”和“值”MySqlCommand *? – 2013-03-04 04:34:25
你不能使用SqlBulkCopy或LINQ to SQL。 – Popeye 2013-03-04 04:35:15
@Debug您对'SqlBulkCopy'的建议可能需要一些评论:*我正在使用我的Sql * – 2013-03-04 04:38:40