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();
}
```
相关推荐
高梦轩15 小时前
MySQL高可用
android·运维·数据库
紫金修道18 小时前
【DeepAgent】概述
开发语言·数据库·python
孟章豪18 小时前
《SQL拼接 vs 参数化,为什么公司禁止拼接SQL?(附真实案例)》
服务器·数据库·sql
荒川之神18 小时前
ORACLE LEVEL函数练习
数据库·oracle
·云扬·19 小时前
【MySQL】实战:用pt-table-sync修复主从数据一致性问题
数据库·mysql·ffmpeg
swIn KWAL19 小时前
【MySQL】环境变量配置
数据库·mysql·adb
shark222222219 小时前
【JOIN】关键字在MySql中的详细使用
数据库·mysql
RATi GORI19 小时前
MySQL中的CASE WHEN语句:用法、示例与解析
android·数据库·mysql
Master_H_ice19 小时前
Claude Code安装试用记录(Windows)
windows·claude code
坊钰19 小时前
Java 死锁问题及其解决方案
java·开发语言·数据库