提问人:Kavi 提问时间:10/18/2023 最后编辑:Kavi 更新时间:10/18/2023 访问量:54
当分配给该命令的连接位于挂起的本地事务中时,ExecuteNonQuery 要求该命令具有事务。在 dbcall 中
ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. in dbcall
问:
这是我的代码;我为命令和添加了事务。但我仍然收到此错误“当分配给命令的连接处于挂起的本地事务中时,ExecuteNonQuery 要求命令具有事务。我尝试以多种方式添加事务,但仍然收到相同的错误。SqlDataAdapter
SqlCommand
using (SqlConnection connection = Database.GetConnection(connString))
{
SqlTransaction transaction = connection.BeginTransaction();
try
{
var batchCommand = new SqlCommand("spname", connection, transaction);
batchCommand.Transaction = transaction;
batchCommand.Parameters.Add("@param1", SqlDbType.Int, 4, dt.Columns[0].ColumnName);
batchCommand.CommandType = CommandType.StoredProcedure;
batchCommand.UpdatedRowSource = UpdateRowSource.None;
SqlDataAdapter adpt = new SqlDataAdapter(batchCommand.CommandText, connection);
adpt.UpdateCommand = batchCommand;
adpt.InsertCommand = batchCommand;
adpt.InsertCommand.Transaction = transaction;
adpt.UpdateCommand.Transaction = transaction;
adpt.UpdateBatchSize = 100;
int recordsImpacted = adpt.Update(dt);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
答:
0赞
Dieu Phan Dinh
10/18/2023
#1
您可以尝试相同的示例:
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
using (SqlTransaction transaction = connection.BeginTransaction())
{
using (SqlCommand batchCommand = new SqlCommand("spname", connection, transaction))
{
try
{
batchCommand.Parameters.Add("@param1", SqlDbType.Int, 4, dt.Columns[0].ColumnName);
batchCommand.CommandType = CommandType.StoredProcedure;
batchCommand.UpdatedRowSource = UpdateRowSource.None;
SqlDataAdapter adpt = new SqlDataAdapter(batchCommand.CommandText, connection);
adpt.UpdateCommand = batchCommand;
adpt.InsertCommand = batchCommand;
adpt.InsertCommand.Transaction = transaction;
adpt.UpdateCommand.Transaction = transaction;
adpt.UpdateBatchSize = 100;
int recordsImpacted = adpt.Update(dt);
batchCommand.ExecuteNonQuery();
transaction.Commit();
}
catch
{
transaction.Rollback();
}
}
}
}
评论
0赞
Kavi
10/20/2023
我试过这个,但没有用。
0赞
Dieu Phan Dinh
10/23/2023
你看到的异常是什么?
0赞
Kavi
11/2/2023
当分配给该命令的连接位于挂起的本地事务中时,ExecuteNonQuery 要求该命令具有事务。
0赞
Dieu Phan Dinh
11/2/2023
您可以尝试添加新的行代码,如下所示:在“try {”块下。batchCommand.Transaction = transaction;
0赞
Dieu Phan Dinh
11/2/2023
如果仍然错误,请在以下代码中添加事务参数:SqlDataAdapter adpt = new SqlDataAdapter(batchCommand.CommandText, connection);
SqlDataAdapter adpt = new SqlDataAdapter(batchCommand.CommandText, connection, transaction);
评论
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand
IDisposable
using