1. 程式人生 > >SqlServer的兩種插入方式效率對比

SqlServer的兩種插入方式效率對比

  protected void button1_Click(object sender, EventArgs e)

        {

            DataTable dtSource = new DataTable();

            dtSource.Columns.Add("Name", typeof(string));

            dtSource.Columns.Add("Address", typeof(string));

 

            DataRow dr;

 

            for (int i = 0; i < 100 * 100; i++)

            {

                dr = dtSource.NewRow();

                dr["Name"] = "Name" + i;

                dr["Address"] = "Address" + i;

 

                dtSource.Rows.Add(dr);

            }

 

            //將記憶體表dt中的1W條資料一次性插入到t_Data表中的相應列中 

            System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();

            st.Start();

            string connStr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

            using (SqlBulkCopy copy = new SqlBulkCopy(connStr))

            {

                //1 指定資料插入目標表名稱 

                copy.DestinationTableName = "Student";

 

                //2 告訴SqlBulkCopy物件 記憶體表中的 OrderNO1和Userid1插入到OrderInfos表中的哪些列中 

                copy.ColumnMappings.Add("Name", "Name");

                copy.ColumnMappings.Add("Address", "Address");

 

                //3 將記憶體表dt中的資料一次性批量插入到OrderInfos表中 

                copy.WriteToServer(dtSource);

            }

            st.Stop();

           this.lblPL.InnerText="資料插入成功,總耗時為:" + st.ElapsedMilliseconds + "毫秒";

 

        }

 

 

protected void button2_Click(object sender, EventArgs e)

        {

            DataTable dtSource = new DataTable();

            dtSource.Columns.Add("ID", typeof(int));

            dtSource.Columns.Add("Name", typeof(string));

            dtSource.Columns.Add("Address", typeof(string));

 

            DataRow dr;

 

            for (int i = 0; i < 100 * 100; i++)

            {

                dr = dtSource.NewRow();

                dr["Name"] = "Name" + i;

                dr["Address"] = "Address" + i;

 

                dtSource.Rows.Add(dr);

            }

 

            System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch(); //計算時間 

            st.Start();

            string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;     //連線資料庫 

            string sqlText = "select * from Student";          //SQL語句,用於查出符合條件的資料庫資料 

 

            //當上述工作完成之後,我們呼叫SqlDataAdapter的Fill()方法,將查詢出來的資料表內容填充的一張DataTable裡面  

            SqlDataAdapter SDA = new SqlDataAdapter(sqlText, conn);

            SDA.Fill(dtSource);

            //這個SqlCommandBuilder用來自動生成新增、刪除、修改的語句,注意這個引數是剛才建立的SqlDataAdapter。 

            SqlCommandBuilder SCB = new SqlCommandBuilder(SDA);

            SDA.Update(dtSource);         //資料錄入 

            st.Stop();

           this.lblCT.InnerText="資料插入成功,總耗時為:" + st.ElapsedMilliseconds + "毫秒";

 

        }