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

    }

  • 相关阅读:
    WSDL
    对协程的理解
    调用webServer
    待看
    BZOJ4668 冷战(并查集)
    BZOJ4651 NOI2016网格(割点)
    Lyft Level 5 Challenge 2018
    BZOJ3073 PA2011Journeys(线段树+bfs)
    BZOJ4602 SDOI2016齿轮(搜索)
    BZOJ4597 SHOI2016随机序列(线段树)
  • 原文地址:https://www.cnblogs.com/jinjingBlog/p/9804125.html
Copyright © 2011-2022 走看看