zoukankan      html  css  js  c++  java
  • Sql-事务

    private void Form1_Load(object sender, EventArgs e)
            {
                SqlConnection con = new SqlConnection(@"SERVER=localhost;UID=sa;DATABASE=GG;MultipleActiveResultSets =true;PWD=123456");
                con.Open();
                ////创建事务并赋值
                SqlTransaction tran= con.BeginTransaction();
                //创建SqlCommand实例
                SqlCommand _delete=con.CreateCommand();
                SqlCommand _insert = con.CreateCommand();
                SqlCommand _select = con.CreateCommand();
                SqlCommand _update = con.CreateCommand();
                //通过同一个SqlConnection创建的SqlCommand,每一个都需要事务,否则报错
                _delete.Transaction = tran;
                _insert.Transaction = tran;
                _select.Transaction = tran;
                _update.Transaction = tran;
    
                try
                {
                    _delete.CommandText = "delete from t_user where no=11 or no=12";
                    _delete.ExecuteNonQuery();
                    _insert.CommandText = "insert t_user (no,age,name) values(11,111,1111)";
                    _insert.ExecuteNonQuery();
                    ////在SQL语句未执行完提交,后面的语句报错不会回滚
                    ////tran.Commit();
                    _update.CommandText = "update t_user set name=12,no=12,age=12 wh2ere no=11";
                    _update.ExecuteNonQuery();
                    _select.CommandText = "select * from t_user";
                    SqlDataAdapter adt = new SqlDataAdapter(_select);
                    DataTable dt = new DataTable();
                    adt.Fill(dt);
                    dataGridView1.DataSource = dt;
                    //提交事务(在与本事务相关sql语句执行完之后提交)
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    //从挂起状态回滚事务,不需要写tran.Rollback();,报错会自动运行
                    //tran.Rollback();
                    MessageBox.Show(ex.Message.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Question);
                }
                finally
                {
                    con.Close();
                }
            }
    

      

  • 相关阅读:
    调试STM32/8 程序一些浅显又不易发现的问题
    MS5611 转换时间和精度的关系
    matlab 实用快捷键
    计算机中十六进制数对应的内存大小速记
    matlab 基本变量和函数
    自定义Button形状(圆形、椭圆)
    Android:自定义标题栏
    Python-21-socket编程
    Python-20-异常处理
    Python-19-元类
  • 原文地址:https://www.cnblogs.com/lhlong/p/4838653.html
Copyright © 2011-2022 走看看