T - SQL使用事务 及 在Winform使用事务

事务适用场景

        1 事务使用在存储过程中,直接在数据库中进行编写
        2 事务使用在Winfrom项目中

SQl:使用事务转账操作的实例

一般都会找一个变量记录错误的个数,@error记录上一句sql的错误和错误编号

declare @errornum int  = 0 -- 定义一个记录错误个数的变量
begin transaction -- 开启事务
	begin
		-- 转出操作
		update Card set CurrentMoney = CurrentMoney - 100000 where StudentId = 1002
		set @errornum = @errornum + @@error -- 把@@error加到总的记录上
		-- 转入操作
		update Card set CurrentMoney = CurrentMoney + 100000 where StudentId = 1004
		set @errornum = @errornum + @@ERROR
		if(@errornum > 0) -- 证明有错误,把之前已经执行的操作回滚到原先的数据上
			rollback transaction -- 回滚事务
		else -- 没有错误,提交事务
			commit transaction
	end
go
select * from Card

声明一个过程 包含三个输入参数 分别是两个转账的卡号 和转账的金额

use YinHangDB
go
create procedure tt10000
	@outZhangHao int,
	@ruZhangHao int,
	@Money int
as
	declare @c1 int = 0--错误的个数
	begin transaction --开启事务
		begin
			--转出
			update Card set CurrentMoney = CurrentMoney - @Money where StudentId = @outZhangHao
			set @c1 = @c1 + @@ERROR

			--转入
			update Card set CurrentMoney = CurrentMoney + @Money where StudentId = @ruZhangHao
			set @c1 = @c1 + @@ERROR
			if(@c1>0)
				rollback transaction
			else 
				commit transaction
		end

go	
select * from Card
--测试转账失败的操作
exec tt10000 1000,1001,100000

--测试转账成功
exec tt10000 1000,1001,50000

Winfrom 使用事故实例

链接SQl 数据库

public string connString = @"Server=.;Database=SMDB;Uid=sa;Pwd=123456";

搭建Winfrom界面

 测试事务回滚的方法

 private void button1_Click(object sender, EventArgs e)
 {
     //删除前学生总个数
     int num1 = (int)GetSingleCount("select count(*) from Students");
     this.listBox1.Items.Add("删除前学生总个数:"+ num1);  // 展示在listbox下


     // 测试删除学生失败进行事务回滚操作

     //定义一个列表字符串 
     List<string> list = new List<string>()
     {
       "delete from Students where StudentId = 1000005",
       "delete from Students where StudentId = 1000024",
       "delete from Students where StudentId = 1000006"
     };

     //执行删除操作 把list里面每一句sql都去执行一下

     int result = 0;
     try
     {
         result = UpdateDataBase(list);
     }
     catch (Exception ex)
     {

         this.listBox1.Items.Add(ex.Message);
     }

     if (result > 0)
     {
         this.listBox1.Items.Add("删除成功");
     }
     else
     {
         this.listBox1.Items.Add("删除失败");
     }
     this.listBox1.Items.Add("删除之后剩余人数为:" + (int)GetSingleCount("select count(*) from Students"));

 }

封装多个删除语句执行操作
参数是多个sql的集合
返回值 int是否执行成功

public int UpdateDataBase(List<string> list)
{
    SqlConnection conn = new SqlConnection(connString);
    //  new SqlCommand(sql, conn)
    //  没有指定执行sql 没有指定连接,下面必须在写代码把连接对象添加上
    SqlCommand cmd = new SqlCommand(); 
    cmd.Connection = conn;
    try
    {
        conn.Open();
        //开启事务
        cmd.Transaction = conn.BeginTransaction();
        int result = 0;//记录删除时候受影响的行数
        //取出每一个sql语句 分别执行
        foreach (string sql in list)
        {
            //设置执行的sql
            cmd.CommandText = sql; 
            result += cmd.ExecuteNonQuery();
         // cmd.ExecuteNonQuery() 返回受影响行数如果删除成功了,受影响行数不为0
        }
        //如果执行错误了 跳转到catch里面 在catch执行回滚
        // 没有出错 提交事务
        cmd.Transaction.Commit();
        return result;
    }
    catch(Exception ex)
    {
        if (cmd.Transaction != null)
        {
            cmd.Transaction.Rollback(); // 执行sql语句有错误的情况 执行回滚操作
        }
        throw new Exception("执行删除sql事务出错:" + ex.Message);
    }
    finally
    {
        // 不管是否执行有误 把事务置为null 清除事务
        if(cmd.Transaction!=null)
        {
            cmd.Transaction = null;
        }
        conn.Close();
    }
}

获取数据库个数的方法

 public object GetSingleCount(string sql)
 {
     SqlConnection conn = new SqlConnection(connString);
     SqlCommand cmd = new SqlCommand(sql, conn);
     conn.Open();
     return cmd.ExecuteScalar();

 }

测试事务提交的方法 

private void button2_Click(object sender, EventArgs e)
{
    //删除前学生总个数
    int num1 = (int)GetSingleCount("select count(*) from Students");
    this.listBox1.Items.Add("删除前学生总个数:" + num1);  // 展示在listbox下


    // 测试删除学生失败进行事务回滚操作

    //定义一个列表字符串 
    List<string> list = new List<string>()
    {
      "delete from Students where StudentId = 1000033",
      "delete from Students where StudentId = 1000031",
      "delete from Students where StudentId = 1000032"
    };

    //执行删除操作 把list里面每一句sql都去执行一下

    int result = 0;
    try
    {
        result = UpdateDataBase(list);
    }
    catch (Exception ex)
    {

        this.listBox1.Items.Add(ex.Message);
    }

    if (result > 0)
    {
        this.listBox1.Items.Add("删除成功");
    }
    else
    {
        this.listBox1.Items.Add("删除失败");
    }
    this.listBox1.Items.Add("删除之后剩余人数为:" + (int)GetSingleCount("select count(*) from Students"));
}

  • 28
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
WinForms 是一个面向 Windows 操作系统的 GUI 应用程序开发框架,它提供了一些工具和组件来帮助开发人员快速创建 Windows 应用程序。事务是指一系列操作的集合,这些操作必须全部成功或全部失败。在 WinForms 中,可以使用事务来确保一个操作集合的原子性,从而避免数据不一致或者错误的情况。 在 WinForms 中,可以使用多种方式实现事务,例如使用数据库事务使用事务性文件系统或者通过编写自定义代码来实现。一般来说,建议使用数据库事务来处理 WinForms 应用程序中的事务管理,因为数据库事务是最常用的事务处理方式之一。 在使用数据库事务时,可以使用 ADO.NET 中的 Transaction 类来管理事务。具体来说,可以通过以下步骤实现 WinForms 应用程序中的事务处理: 1. 创建一个连接对象并打开连接。 2. 创建一个事务对象并将其与连接对象关联。 3. 执行一系列数据库操作,例如插入、更新或删除数据。 4. 如果所有操作成功,则提交事务;如果任何一个操作失败,则回滚事务。 5. 关闭连接对象。 例如,下面的代码演示了如何使用事务数据库中插入一条记录: ```csharp using (var connection = new SqlConnection(connectionString)) { connection.Open(); using (var transaction = connection.BeginTransaction()) { try { var command1 = new SqlCommand("INSERT INTO Customers (Name, Email) VALUES ('Alice', 'alice@example.com')", connection, transaction); var command2 = new SqlCommand("INSERT INTO Orders (CustomerId, ProductName) VALUES ((SELECT MAX(Id) FROM Customers), 'Product A')", connection, transaction); command1.ExecuteNonQuery(); command2.ExecuteNonQuery(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); MessageBox.Show("An error occurred: " + ex.Message); } } } ``` 在这个例子中,我们首先创建了一个 SqlConnection 对象并打开了连接。然后,我们使用 BeginTransaction 方法创建了一个事务对象,并将其与连接对象关联。接下来,我们执行了两个 SQL 命令,分别向 Customers 表和 Orders 表插入数据。最后,我们在 try-catch 块中提交事务或者回滚事务,具体取决于操作是否成功。最后,我们关闭连接对象。 总之,WinForms 应用程序中的事务处理是一个非常重要的方面,它可以帮助我们确保数据库操作的原子性和一致性。通过使用数据库事务,我们可以轻松地实现事务处理,并避免数据不一致或者错误的情况。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值