zoukankan      html  css  js  c++  java
  • sql事务、ado事务

    sql server事务
    begin try
    begin transaction --开始事务
    update UserInfo set UserName='你好' where UserId=2
    update UserInfo set UserAge='你好' where UserId=3
    commit transaction --提交事务
    end try

    begin catch
    rollback transaction --回滚事务
    end catch

    ado 事务
    第一种写法
    string str ="连接数据库";
    using(SqlConnection conn =new SqlConnection(str))
    {
    using(SqlCommand cmd=conn.CreateCommand())
    {
    conn.Open();
    SqlTransaction trans = conn.BeginTranscation();
    //创建事务对象
    try
    {
    cmd.CommandText = @"update UserInfo set UserName='你好' where UserId=2
    update UserInfo set UserAge='你好' where UserId=3";
    cmd.Transaction = trans;
    cmd.ExecuteNonQuery();

    SqlCommand cmd2 =conn.CreateCommand();
    cmd2.CommandText = @"update UserInfo set UserAge=UserAge+1 where UserId=4
    cmd2.Transaction = trans;
    cmd2.ExecuteNonQuery();
    }
    catch(Exception ex)
    {
    trans.Rollback();//回滚事务
    }
    }
    }
    第二种写法
    添加引用 System.Transactions
    try
    {
    using(TransactionScope scope=new (TransactionScope ())
    {
    string str ="连接数据库";
    using(SqlConnection conn =new SqlConnection(str))
    {
    using(SqlCommand cmd=conn.CreateCommand())
    {
    conn.Open();

    cmd.CommandText = @"update UserInfo set UserName='你好' where UserId=2
    update UserInfo set UserAge='你好' where UserId=3";
    cmd.ExecuteNonQuery();
    }
    }
    scope.Complete();//提交事务
    }
    }
    catch(Exception ex)
    {

    }

  • 相关阅读:
    时间选择框(可用于Form)
    点击复制指定内容
    ajax中多个模板之间套用ajax
    Java学习路径
    Windows平台安装Python
    Python语法-第2关
    Python语法-第1关
    Python语法-第0关
    图像识别
    wx:for用法
  • 原文地址:https://www.cnblogs.com/jinjingBlog/p/9804125.html
Copyright © 2011-2022 走看看