• 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)
    {

    }

  • 相关阅读:
    Matplotlib绘制漫威英雄战力图,带你飞起来!
    jupyter渲染网页的3种方式
    MySQL全文索引、联合索引、like查询、json查询速度大比拼
    进一步聊聊weight initialization
    深度学习基础(2)
    深度学习基础(1)
    SLAM的前世今生
    深度学习:识别图片中的电话号码(1)
    tf更新tensor/自定义层
    tf训练OTSU
  • 原文地址:https://www.cnblogs.com/jinjingBlog/p/9804125.html
Copyright © 2020-2023  润新知