C#SqlTransaction.Commit抛出异常,因为Connection为null

时间:2012-05-11 10:36:11

标签: c# database-connection sqltransaction

使用SqlTransaction时遇到问题。这是代码

SqlConnection conn = new SqlConnection(connectionString);
// assume that at this point I add try/catch and the connection is successfully opened.
conn.Open();
SqlTransaction trans = conn.BeginTransaction(IsolationLevel.RepeatableRead);

//.........
// Here I do my action with database, change it, commit, call ExecuteNonQuery, //ExecuteScalar,etc...

// And after that long processing with this transaction, I don't know why trans.Connection //is null. and therefore when I call trans.commit(), an exception was raised?


trans.commit();

有人有线索吗?

我认为这可能是因为数据库服务器的内存因为连接太多而耗尽。但我不确定。

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

似乎错字

con.BeginTransaction(IsolationLevel.RepeatableRead)

应该是

conn.BeginTransaction(IsolationLevel.RepeatableRead)

答案 1 :(得分:1)

使用

using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
        Console.WriteLine("State: {0}", connection.State);
    }

答案 2 :(得分:0)

使用using声明:

using (SqlConnection connection = new SqlConnection(connectionString))
{
//your code here
}

答案 3 :(得分:0)

c# - catch事务连接后的SqlTransaction为null - Stack Overflow SqlTransaction after catch transaction connection is null

Edyn说: 陷入类似的问题。就我而言,它发生在特定的SqlException上。大多数异常都会被捕获并处理得很好,但每当我遇到转换错误(例如尝试将字符串转换为数字)时,它都会自动结束事务。

在我的解决方案中,如果发现底层连接为null,我将重建transacton。但这是一项肮脏的工作。