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

    }

  • 相关阅读:
    go语言入门(三)
    go语言入门(二)
    Nand Flash 基础
    哈希技术
    NorFlash基础
    二阶构造模式
    C++基础知识汇总
    Arm寄存器介绍及汇编基础
    Linux Makefile详解
    Linux链接器脚本详解
  • 原文地址:https://www.cnblogs.com/jinjingBlog/p/9804125.html
Copyright © 2011-2022 走看看