在ASP.NET中,向数据库批量插入数据

 我们平时的开发过程中,经常要向数据库插入数据,有时可能要进行很多次类似的操作,比如向数据库中的同一个表同时插入若干数据,即批量插入数据。

向数据库中批量插入数据,可以将若干条数据一次插入道数据库,提高程序的执行效率,也可以减少我们的工作量。

批量插入数据,可以采用一下两种方法。

一、利用事务(Transaction

定义执行批量插入数据的函数,参数为Insert SQL语句的数组

 Sub ExeTransaction (Byval Sqlstrlist as string())

          Dim Conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Tax.mdb"

          Dim trans as OledbTransaction=Nothing

          Try

                If conn.State=connectionstate.closed then

Conn.open()

                    End if

Dim cmd as oledbCommand=new oledbcommand()

cmd.connection=conn

cmd.commandtype=commandtype.text

trans=conn.BeginTransaction()

cmd.Transaction=trans

dim I as integer

 for I=0 to Sqlstrlist.GetupperBound(0)

       cmd.commandText= Sqlstrlist(i) 取得参数(数组)中的值

       cmd.ExecuteNonQuery()

Next

Trans.commit()

Catch ex as oledbexception

     Trans.Rollback()

Fanlly

     Conn.close()

End try

      End sub

二、利用Dataset

public sub Insert()

     建立datatable数据源

   dim dt as DataTable=New DataTable()

   Dim dr as DataRow

   Dt.Columns.Add(new DataColumn(“name”))

Dim j as Integer

For j =0 to 10

   Dr=dt.newrow()

   Dr(0)=”name”+j.toString

Dt.Rows.Add(dr)

Next

      Dim Conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Tax.mdb"

Conn.open()

Dim MyAdapter as Oledbdataadapter=new OleDataAdapter()

….

Dim cmd as Oledbcommand=New Oledbcommand(“Insert Into table(name) values (@name)”,conn)

cmd.parameters.item(“@name”).SourceColumns=dt.columns(“name”).columnsName

myAdapter.update(dt)

conn.close()

end sub

利用以上的两种方法,都可以完成向数据库批量插入数据。



//////////////////////////////例
  List<string> sSqls = new List<string>();           
            int iMenuLine = Convert.ToInt32(_oOpenedTableInfo["menu_line"]) ;
            foreach (CSelDish oSelDish in _oLstSelDish)
            {
                //p_insertSellDetail( @userid @sysno  @menu_line  @menucode @menu_cname @numbers@price @unit @markdesc @setflag @largessflag @OpType @IsOK)                               
                iMenuLine++;
                sSqls.Add(String.Format("exec p_insertSellDetail {0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}",
                                _oCommon.procStr(_oCommon.UserID), _oCommon.procStr(_oOpenedTableInfo["sysno"]),
                                iMenuLine, _oCommon.procStr(oSelDish.DishNo), _oCommon.procStr(oSelDish.DishName), oSelDish.Qty,
                                oSelDish.Price, _oCommon.procStr(oSelDish.Unit), _oCommon.procStr(oSelDish.Remark),
                                _oCommon.procStr(oSelDish.IsSet), _oCommon.procStr(oSelDish.CanLargess), 0, 1));               
                if (oSelDish.IsLargess)
                {
                    sSqls.Add(String.Format("exec p_insertSellDetail {0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}",
                                _oCommon.procStr(_oCommon.UserID), _oCommon.procStr(_oOpenedTableInfo["sysno"]),
                                iMenuLine, _oCommon.procStr(oSelDish.DishNo), _oCommon.procStr(oSelDish.DishName), oSelDish.Qty,
                                oSelDish.Price, _oCommon.procStr(oSelDish.Unit), _oCommon.procStr(oSelDish.Remark),
                                _oCommon.procStr(oSelDish.IsSet), _oCommon.procStr(oSelDish.CanLargess), 2, 1));                   
                }
            }
            if (_oLstSelDish.Count > 0)
                sSqls.Add("update opentables set menu_line=0" + iMenuLine + " where sysno=" + _oCommon.procStr(_oOpenedTableInfo["sysno"]));
            try
            {
                DataClass.CDataInterface oDA = new MidasTouch.DataClass.CDataInterface();
                oDA.beginExec();
                foreach (string s in sSqls)               
                    oDA.execSql(s);                               
                oDA.endExec();//事务
                _oOpenedTableInfo["menu_line"] = iMenuLine;
                ClearSelDish();
                _bsendDish = true;
               // this.DialogResult = DialogResult.Yes;             
                return true;
            }
            catch (Exception ex)
            {
                _oCommon.ShowInfo("发送失败:"+ex.Message);
                return false;
            }
///////////////
  /// <summary>
        /// 执行一段SQL语句
        /// </summary>
        /// <param name="sSql"></param>
        /// <returns>返回受影响的行数</returns>
        public int execSql(string sSql)
        {
            SqlCommand oCmd = new SqlCommand(sSql, _oConn);
            oCmd.Transaction = _oTran;
            return oCmd.ExecuteNonQuery();
        }
////////////////
  /// <summary>
        /// 准备开始执行
        /// </summary>
        public void beginExec()
        {
            _oConn = new SqlConnection();
            _oConn.ConnectionString = _oCommon.ConnStr;
            _oConn.Open();
            _oTran = _oConn.BeginTransaction();
        }
////////////////////
   /// <summary>
        /// 结束执行
        /// </summary>
        public void endExec()
        {
            _oTran.Commit();
            _oConn.Close();
        }
/////////////////
 /// <summary>
        /// 取消执行
        /// </summary>
        public void cancelExec()
        {
            if (_oConn != null)
            {
                if (_oTran != null)
                    _oTran.Rollback();
                _oConn.Close();
            }
        }  

posted on 2007-01-29 15:27  玄新  阅读(1135)  评论(0编辑  收藏  举报

导航