在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对象一起使用,并且事务完成后应将其释放。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: c# halcon在安防监控中的应用