关于SQL语句的批量执行

SQL语句的执行可以分为三种的方法进行批量执行。这里主要介绍使用事务机制批量执行语句。

      这个函数是在windows service 上编写的。

 public void InsertAll(List<string> SqlAll)
        {
            SqlConnection connetion=this.SqlConn();                     //创建数据库连接
            SqlTransaction transaction=null;                                   //声明事务
            SqlCommand command=null;

            try{
                connetion.Open();                                                     //打开数据库连接
                transaction=connetion.BeginTransaction();             //使用数据库连接创建事务
                command=connetion.CreateCommand();
                command.Transaction=transaction;                          

                try{
                    for(int i=0;i<SqlAll.Count;i++)
                    {
                        if(!string.IsNullOrEmpty(SqlAll[i]))                        //判断当前SQL语句是否为空
                        {
                            command.CommandText=SqlAll[i];
                            command.ExecuteNonQuery();
                        }
                    }
                    transaction.Commit();                                               //事务提交
                }
                catch(Exception ex)
                {
                    transaction.Rollback();                                            //事务撤销
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
                finally
                {
                    connetion.Close();
                }
               
            }
            catch(Exception ee)
            {
                System.Diagnostics.Debug.WriteLine(ee.Message);
            }

        }

 

          通过事务机制保证批量的数据能够正确执行,如果任何一个SQL执行错误就会撤销本次事务,通过事务SQL语句的批量执行主要通过的SQLCOMMAND来完成,这避免了数据库连接的不断打开和关闭操作,执行效率比较高。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

踏雪_无痕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值