111,119
社区成员
发帖
与我相关
我的任务
分享using(SqlConnection sqlConnection = new SqlConnection(connectionString))
{
........
} sqlConnection.Open();
using(var trans= sqlConnection.BeginTransaction())
{
command.Transaction= trans;
command.ExecuteNonQuery();
trans.Commit();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=pgo_swsvr\\pgo_swsvr_scai;Initial Catalog=pubs;Persist Security Info=True;User ID=sa;Password=sa";
SqlConnection sqlConnection = new SqlConnection(connectionString);
string strSQL = " insert into discounts values('test', NULL, NULL, NULL, 'aaa')";
SqlCommand command = new SqlCommand(strSQL, sqlConnection);
string strSQL1 = " insert into discounts values('test', NULL, NULL, NULL, 11.22)";
SqlCommand command1 = new SqlCommand(strSQL1, sqlConnection);
sqlConnection.Open();
SqlTransaction transaction = command.Connection.BeginTransaction();
command.Transaction = transaction;
command1.Transaction = transaction;
try
{
command1.ExecuteNonQuery();
//这个时候transaction是好的
//debug时能看到IsolationLevel是readcommitted, Connection是正常值
command.ExecuteNonQuery();
command.Transaction.Commit();
}
catch(Exception ex)
{
//异常是Error converting data type varchar to numeric.
//这个时候transaction已经不在正常状态下了
//debug时看到Connection是null了
//IsolationLevel是IsolationLevel = 'transaction.IsolationLevel' threw an exception of type 'System.InvalidOperationException'
//而异常信息是{System.SystemException} = {"This SqlTransaction has completed; it is no longer usable."}
//个人推断transaction已经被自动rollback了
transaction.Rollback();
//显式执行Rollback也没有异常
command.Transaction.Rollback();
}
finally
{
sqlConnection.Close();
}
}