问题描述
我在事务中插入了一系列插入内容,然后进行了提交。如果我在关闭连接之前使用WITH(READUNCOMMITTED)查询数据库,它将按预期显示。但是,关闭连接后,数据消失。为什么交易实际上没有提交?
using (sqlConnection db = new sqlConnection(connectionstring))
{
db.open();
sqlTransaction transaction = db.BeginTransaction("loadrate");
try
{
int id = 0;
using (sqlDataAdapter da = new sqlDataAdapter("usp_1",db))
{
da.SelectCommand.Transaction = transaction;
da.SelectCommand.CommandType = CommandType.StoredProcedure;
id = (int)da.SelectCommand.ExecuteScalar();
}
int id2 = 0;
using (sqlDataAdapter da = new sqlDataAdapter("usp_2",db))
{
da.SelectCommand.Transaction = transaction;
da.SelectCommand.CommandType = CommandType.StoredProcedure;
id2 = (int)da.SelectCommand.ExecuteScalar();
}
transaction.Commit();
Console.WriteLine("Committed data");
}
catch (Exception insertExcept)
{
Console.WriteLine("Exception: " + insertExcept.Message + ". Rolling Back");
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}",ex2.GetType());
Console.WriteLine(" Message: {0}",ex2.Message);
}
}
finally
{
db.Close();
}
}
解决方法
向@mason致以正确的方向。其中一个存储过程中有未提交的事务,而.net的Commit无法关闭该事务,关闭连接会自动将其回滚。谢谢您的帮助!