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();
}
```
相关推荐
我是大猴子16 分钟前
Stream流式编程
数据库·sql
Bert.Cai17 分钟前
Oracle ASCII函数详解
数据库·oracle
跨境猫小妹19 分钟前
多国海关字段持续细化后跨境卖家如何搭建商品信息映射表
大数据·数据库·人工智能·跨境电商·跨境·营销策略
峥无22 分钟前
MySQL 最全数据类型详解(数值/字符串/日期/枚举集合)
数据库·mysql
IT策士27 分钟前
Redis 从入门到精通:Redis Sentinel 哨兵
数据库·redis·sentinel
LAM LAB29 分钟前
【Quicker】拆分文本,按行读取文本执行循环写入
windows·quicker
云器科技32 分钟前
螳螂科技:从组装到统一,如何用云器 Lakehouse 完美替代“MC+DW+ADB”三件套?
数据库·数据仓库·人工智能
Amnesia0_034 分钟前
MySQL的访问和数据流动
数据库·mysql
AI2中文网37 分钟前
App Inventor 2 数据库方案全览:从本地存储到云端服务
数据库·oracle·app inventor
Arbori_2621538 分钟前
找回mysql root 密码
数据库·mysql