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();
}
```
相关推荐
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
rockmelodies5 天前
# Windows Server2008 R2 Standard(SP1镜像U盘)重置本地管理员密码【完整详细步骤】
windows·密码破解
神仙别闹5 天前
基于C#+MySQL实现(WinForm)个人聊天室软件
c#
这个DBA有点耶5 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
DBA_G5 天前
从地面到云霄:GBase数据库在民航三大场景的落地实践
数据库
自由能燃气设备5 天前
商用全预混低氮冷凝锅炉免费方案vs付费方案对比+选型避坑指南
大数据·数据库·人工智能
科创致远5 天前
科创致远 ESOP 系统核心效能与实战价值展示
大数据·数据库·人工智能·精益工程
漂着的圆木5 天前
Agent 功能参与度:Copilot 怎么算
sql·数据分析·agent·githubcopilot·度量
kybs19915 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net
2601_962218615 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法