使用SqlTransaction时关闭SqlConnection

本文关键字:SqlConnection SqlTransaction 使用 | 更新日期: 2023-09-27 18:21:31

我正在使用SqlTransaction执行一系列插入命令-

connection.Open();
transaction = connection.BeginTransaction();
command.Transaction = transaction;
command.CommandText="Insert into ....";
connection.Close();
//Doing some other task and then again open connection.
connection.Open();
command.CommandText="Insert into ....";
connection.Close(); 

最后,

transaction.Commit();
if (transaction != null) { transaction.Rollback(); }

我的问题是,我可以在使用事务时关闭该连接吗?我一定需要回滚能力。

有什么帮助吗?

使用SqlTransaction时关闭SqlConnection

您可以在事务完成后关闭连接。低于

class Transaction
 {
     public Transaction()
     {
        string FirstQuery = "INSERT INTO Table1 VALUES('Vineeth',24)";
        string SecondQuery = "INSERT INTO Table2 VALUES('HisAddress')";
        int ErrorVar = 0;
        using (SqlConnection con = new SqlConnection("your connection string"))
        {
            try
            {
                SqlCommand ObjCommand = new SqlCommand(FirstQuery, con);
                SqlTransaction trans;
                con.Open();
                trans = con.BeginTransaction();
                ObjCommand.Transaction = trans;
                //Executing first query
                //What ever operation on your database do here
                ObjCommand.ExecuteNonQuery();  //Exected first query
                ObjCommand.CommandText = SecondQuery;
                ObjCommand.ExecuteNonQuery();  //Exected first query
               //Everything gone fine. So commiting
               ObjCommand.Transaction.Commit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error but we are rollbacking");
                ObjCommand.Transaction.Rollback();
            }
            con.Close();
        }
    }
}

或者您可以使用TransactionScope