本文介绍了数据库操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static bool ExecuteQry(string qry, SqlConnection cnn, SqlTransaction SqlT)
		{
			bool Result=true;
			try
			{
                if (cnn.State != ConnectionState.Open)
                {
                    cnn.Open();
                }
                SqlCommand cmd = new SqlCommand(qry, cnn, SqlT);
				cmd.ExecuteNonQuery();
                cmd.Dispose();
                cnn.Close();
			}
			catch(Exception e)
			{

				Result=false;
			}
			return(Result);
		}




执行此代码时,发生以下异常
该事务与当前连接不关联或已完成"
它怎么解决

在此先感谢




When execute this code the following exception is occur
"The transaction is either not associated with current connection or has been completed"
How can it solve

Thanks in advance

推荐答案

sqlTransaction = sqlConnection.BeginTransaction(); 



我为您提供了一个示例代码,您可以遵循以下代码:



I''ve provided you a sample code which you could follow:

public MyMethod()
{
	SqlConnection sqlConnection = null;
        SqlTransaction sqlTransaction = null;
        try
        {
            //Get Connection object
            sqlConnection = GetDataConnection();
            //Obtain SqlTransaction object from Connection object
            sqlTransaction = sqlConnection.BeginTransaction();

            MyMethod1(Input, sqlConnection, sqlTransaction)
            MyMethod2(Input, sqlConnection, sqlTransaction)

            sqlTransaction.Commit();
        }
        catch(Exception e)
        {
            if (sqlTransaction!=null) {sqlTransaction.Rollback()};
            throw new Exception("Failure in method x", e) ;
        }
        finally
        {
            if(sqlConnection!=null && sqlConnection.State==ConnectionState.Open)
            {
                sqlConnection.Close();
            }
        }
}



希望对您有帮助



Hope this helps


这篇关于数据库操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-25 14:54