c# - 关于 sqlTransaction 操作的说明
问题描述
我对事务的理解是,它是一个或多个 SQL 命令,都将作为一个组执行。
现在,我正在阅读Microsoft 的文档,但我不明白第一个try-catch
异常块的目标。如果事务失败,我们为什么要尝试回滚事务。我的意思是,如果它失败了,那么我们不应该肯定数据库中没有进行任何更改(因为这是事务的目标)?我不明白什么?
private static void ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
command.ExecuteNonQuery();
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
command.ExecuteNonQuery();
// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception ex)
{
// Logging exception details
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// Logging exception details
}
}
}
}
解决方案
或者查看system.transactions.transactionscope
它可以在 Using 中使用,如果未完成将回滚而无需回滚命令。
推荐阅读
- python - 用于匹配 XX/YY 字符串但不匹配 XX/YY/ZZ 字符串的正则表达式
- python - 每个帖子标题的 Python Scrape 论坛
- c++ - STL“sort()”排序不充分
- postgresql - Postgresql 选择热敏打印机
- python-3.x - 将新文档添加到现有集群中
- python - 立即销毁 tkinter 按钮和菜单
- python - TypeError:Series 类型的对象不是 JSON 可序列化的
- python - Django:获取模型类的字段名称
- css - CSS 中 SVG 过滤器的奇怪错误
- bash - Bash 每 X 秒读取一次消息