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();
                }
            }
  • 相关阅读:
    Matplotlib中柱状图bar使用
    python IDLE颜色设置
    linux报错汇总
    PCA
    高斯混合模型
    深度解剖dubbo源码---01dubbo的架构原理-探索.mp4
    SpringCloud之初识Feign
    第七模块 :微服务监控告警Prometheus架构和实践
    第四模块 :微服务调用链监控CAT架构和实践
    skywalking中文文档
  • 原文地址:https://www.cnblogs.com/dj1232090/p/2041701.html
Copyright © 2011-2022 走看看