在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對象一起使用,并且事務完成后應將其釋放。