zoukankan      html  css  js  c++  java
  • C#事物处理

    对两个数据表同时进行insert操作处理,对它们的插入操作要么全部成功,要么都插入失败,否则只插入一个表成功会引起数据库的不一致。很显然,这是一个事务处理(transcation),要么commit成功,要么则rollback。在代码中,利用C#中提供的Transcation类来实现,代码如下:

            private void btn_submit_Click(object sender, System.EventArgs e)
            {
                string strconn = ConfigurationSettings.AppSettings["dsn"];
                SqlConnection cnn = new SqlConnection(strconn);
                SqlCommand cmd = new SqlCommand();
                SqlTransaction transaction = null;

                try
                {
                    cnn.Open();
                    // 先插入分店shop表,再插入经理Manager表,并将其作为一个事务进行处理
                    transaction = cnn.BeginTransaction();
                    cmd.Transaction = transaction;
                    cmd.Connection = cnn;

                    // 插入分店shop表
                    string shopstr = "insert into shop values('" + tbx_shopid.Text + "','" + tbx_shopname.Text + "','" + tbx_shopaddress.Text + "','" + tbx_shopphone.Text + "')";
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = shopstr;
                    cmd.ExecuteNonQuery();

                    // 插入经理Manager表
                    string managerstr = "insert into manager values('" + tbx_managerid.Text + "','" + tbx_managerpassword.Text + "','" + tbx_managername.Text + "','" + tbx_shopid.Text + "')";
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = managerstr;
                    cmd.ExecuteNonQuery();

                    // 提交事务
                    transaction.Commit();
                    lbl_msg.Text = "添加分店操作成功";
                }
                catch(Exception ex)
                {
                    lbl_msg.Text = "添加分店操作失败";
                    transaction.Rollback();
                }
                finally
                {
                    cnn.Close();
                }
            }
  • 相关阅读:
    .net WebApi中使用swagger
    HTTP Error 503. The service is unavailable
    python3消费rocketmq
    docker安装部署showdoc
    EasyMock.replay()有什么用
    java.lang.IllegalStateException: 1 matchers expected, 5 recorded.
    io.spring.platform继承方式和import方式更改依赖版本号的问题
    spring-boot-dependencies、spring-boot-starter-parent、io.spring.platform详解
    springboot依赖的一些配置:spring-boot-dependencies、spring-boot-starter-parent、io.spring.platform
    一个最简单的springboot
  • 原文地址:https://www.cnblogs.com/dj1232090/p/2041701.html
Copyright © 2011-2022 走看看