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();
}
```
相关推荐
一叶飘零_sweeeet2 分钟前
MySQL高可用生产落地全解:主从同步、MGR集群、读写分离从原理到实战
数据库·mysql·架构·mysql高可用
qqty12176 分钟前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
2401_8955213412 分钟前
MySQL中between and的基本用法
android·数据库·mysql
brucelee18612 分钟前
Install OpenLM AI module management on Windows
人工智能·windows
2301_8101609513 分钟前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python
wenlonglanying13 分钟前
MySQL事件功能简介
数据库·mysql
l1t18 分钟前
DeepSeek总结的用 C# 构建 DuckDB 插件说明
前端·数据库·c#·插件·duckdb
czlczl2002092518 分钟前
Redis过期删除策略
数据库·redis·缓存
2401_8916558120 分钟前
ZLibrary反爬机制概述
数据库·python
醇氧29 分钟前
第一、二、三范式学习
数据库·学习·oracle