Bic*_*ick 17 .net c# sql-server
我有一个庞大的INSERT INTO ...
字符串列表.目前我运行它们:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
foreach (var commandString in sqlCommandList)
{
SqlCommand command = new SqlCommand(commandString, connection);
command.ExecuteNonQuery();
}
}
Run Code Online (Sandbox Code Playgroud)
我看到每个ExecuteNonQuery()
也执行提交.
Moh*_*zen 35
如果你在一个线程中执行多个查询,建议使用SQL事务,你可以像这样:
SqlTransaction trans;
try
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
trans = connection.BeginTransaction();
foreach (var commandString in sqlCommandList)
{
SqlCommand command = new SqlCommand(commandString, connection,trans);
command.ExecuteNonQuery();
}
trans.Commit();
}
catch (Exception ex) //error occurred
{
trans.Rollback();
//Handel error
}
Run Code Online (Sandbox Code Playgroud)
Ger*_*o H 11
您可能只使用一个事务和命令就可以获得一些性能,如下所示:
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
using (SqlTransaction trans = connection.BeginTransaction())
{
using (SqlCommand command = new SqlCommand("", connection,trans))
{
command.CommandType = System.Data.CommandType.Text;
foreach (var commandString in sqlCommandList)
{
command.CommandText = commandString;
command.ExecuteNonQuery();
}
}
trans.Commit();
}
}
catch (Exception ex) //error occurred
{
//Handel error
}
}
Run Code Online (Sandbox Code Playgroud)
Shy*_*hah -2
您可以对每个使用并行
using (SqlConnection connection = new SqlConnection(connectionString))
{
List<string> sqlCommandList = new List<string>();
connection.Open();
Parallel.ForEach(sqlCommandList, commandString =>
{
SqlCommand command = new SqlCommand(commandString, connection);
command.ExecuteNonQuery();
});
}
Run Code Online (Sandbox Code Playgroud)