C#操作SqlServer数据库事务

操作事务

复制代码
```cs
// 1.连接数据库
string connstring = @"Server = 李昊轩-212\MSSQLSERVER11;Database = Student;uid = sa;Pwd= 123456";
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
// 2.创建多个sql语句
List<string> list = new List<string>() {
    "delete from XueSheng where StudentId = 1004",
    "delete from XueSheng where StudentId = 100"
};
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
try
{
    // 3.开启事务
    cmd.Transaction = conn.BeginTransaction();
    foreach (string s in list)
    {
        // 4.设置执行的sql
        cmd.CommandText = s;
        cmd.ExecuteNonQuery();
    }
    // 5. 如果没有出错 提交事务
    cmd.Transaction.Commit();
}
// 6. 如果执行错误 跳转到catch里面 在catch执行回滚
catch (Exception e)
{
    if (cmd.Transaction != null)
    {
        cmd.Transaction.Rollback(); // 执行sql语句有错误的情况 执行回滚操作
    }
    throw new Exception("执行删除sql事务出错:" + e.Message);
}
finally
{
    // 7.不管是否执行有误 把事务设置为null 清除事务
    if(cmd.Transaction!= null)
    {
        cmd.Transaction = null;
    }
    conn.Close();
}
```
相关推荐
SelectDB16 小时前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc
这个DBA有点耶17 小时前
GROUP BY优化全解:如何写出既不丢数据又飞快的分组查询
数据库·mysql·架构
掉头发的王富贵20 小时前
【StarRocks】极限十分钟入门StarRocks
数据库·sql·mysql
Nturmoils20 小时前
WHERE 条件别凭习惯写,常用查询先跑一遍
数据库
Databend2 天前
在 AWS 中国峰会逛了一天,我在 Databend 展台看到了 Agent 数据基础设施的新思路
数据库·人工智能·agent
雨落倾城夏未凉2 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
ClouGence3 天前
Oracle 数据同步为什么会出现数据不一致?长事务是常被忽略的原因
数据库·后端·oracle
唐青枫3 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
飞将3 天前
从零实现数据库(2)——HashIndex + IndexManager
数据库
唐青枫4 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net