数据库操作 [英] Database Operation

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

问题描述

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.在您的情况下,SqlTransaction 属于另一个SqlConnection,因此,它将引发此类异常消息.

您需要使用以下代码从SqlConnection obejct获取SqlTransaction :

An SqlTransaction should be used for a particular SqlConnection. In your case, the SqlTransaction belongs to another SqlConnection, and hence, it is throwing such Exception message.

You need to obtain the SqlTransaction from the SqlConnection obejct, by using the following piece of code:

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


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆