我如何实现批量update/insert使用SQLCommand.我想用C#SQLCommand中的for循环动态创建文本MyObject[]SQLParameter
在批量的情况下insert,我需要检查它已经存在或不存在的每条记录.即
if not Exists(select pkid from table1 where fkid1=@fkid1 and fkid2=@fkid1)
begin
insert....
Run Code Online (Sandbox Code Playgroud)
end
这是从C#中完成的.没有db中的存储过程
Sau*_*abh 16
SqlCommand command = new SqlCommand();
// Set connection, etc.
for(int i=0; i< items.length; i++) {
command.CommandText += string.Format("update mytable set s_id=@s_id{0} where id = @id{0};", i);
command.Parameters.Add("@s_id" + i, items[i].SId);
command.Parameters.Add("@id" + i, items[i].Id);
}
command.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)
只将CommandTexts一个大批量命令附加到所有内容并不像它看起来那么有用.
C#中预准备语句的主要好处是,在创建命令时完成数据库中的工作负载.不是,当你执行它时[例如,ExecuteNonQuery()只有当你没有创建一个事务对象时才执行命令].
为了避免这种情况并且仅为所有语句在数据库中创建一次工作负载,创建Transaction对象和提交此事务的重要性更高.然后,在数据库中不再有任何工作量的情况下执行所有命令.
这将是一个更好的方法:
// Try to create the Command as early as possible with a valid Connection object
string commandString = "UPDATE Mytable SET s_id=@s_id where id = @id;";
var command = new SqlCommand(commandString, connection);
// Then define a Transaction object with your Connection
var transaction = connection.BeginTransaction();
command.Transaction = transaction;
// Now iterate through your array
for(int i=0; i<array.Length; i++)
{
command.Parameters.Add("@s_id", SqlDbType.YourType).Value = items[i].SId;
command.Parameters.Add("@id", SqlDbType.YourType).Value = items[i].Id;
command.ExecuteNonQuery(); // Not executed at this point
}
// And now execute it with the possibility to rollback all commands when it fails
try { transaction.Commit(); } // Here the execution is committed to the DB
catch (Exception)
{
transaction.Rollback();
throw;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18416 次 |
| 最近记录: |