在C#中,可以使用以下步骤来使用SqlTransaction:
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand command = new SqlCommand(sqlQuery, connection, transaction);
command.ExecuteNonQuery();
transaction.Commit();
或
transaction.Rollback();
connection.Close();
以下是一个完整的示例代码:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlTransaction transaction = connection.BeginTransaction())
{
try
{
SqlCommand command = new SqlCommand(sqlQuery, connection, transaction);
command.ExecuteNonQuery();
// 根据需要提交或回滚事务
transaction.Commit();
}
catch (Exception ex)
{
// 发生异常时回滚事务
transaction.Rollback();
Console.WriteLine(ex.Message);
}
}
}
请注意,SqlTransaction应始终与SqlConnection对象一起使用,并且事务完成后应将其释放。