我正在使用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(); }
我的问题是,我可以在使用交易时关闭该连接吗? 我必须要有RollBack能力。
任何帮助?
答案 0 :(得分:0)
您可以在事务完成后关闭连接。类似下面的内容
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