乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      SQL Server 批量插入數(shù)據(jù)的兩種方法

       kittywei 2012-02-24

      在SQL Server 中插入一條數(shù)據(jù)使用Insert語句,但是如果想要批量插入一堆數(shù)據(jù)的話,循環(huán)使用Insert不僅效率低,而且會導致SQL一系統(tǒng)性能問題。下面介紹SQL Server支持的兩種批量數(shù)據(jù)插入方法:Bulk和表值參數(shù)(Table-Valued Parameters)。

      運行下面的腳本,建立測試數(shù)據(jù)庫和表值參數(shù)。

      [c-sharp] view plaincopy?
      1. --Create DataBase  
      2. create database BulkTestDB;  
      3. go  
      4. use BulkTestDB;  
      5. go  
      6. --Create Table  
      7. Create table BulkTestTable(  
      8. Id int primary key,  
      9. UserName nvarchar(32),  
      10. Pwd varchar(16))  
      11. go  
      12. --Create Table Valued  
      13. CREATE TYPE BulkUdt AS TABLE  
      14.   (Id int,  
      15.    UserName nvarchar(32),  
      16.    Pwd varchar(16))  

       

      下面我們使用最簡單的Insert語句來插入100萬條數(shù)據(jù),代碼如下:

      [c-sharp] view plaincopy?
      1. Stopwatch sw = new Stopwatch();  
      2.   
      3. SqlConnection sqlConn = new SqlConnection(  
      4.     ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);//連接數(shù)據(jù)庫   
      5.   
      6. SqlCommand sqlComm = new SqlCommand();  
      7. sqlComm.CommandText = string.Format("insert into BulkTestTable(Id,UserName,Pwd)values(@p0,@p1,@p2)");//參數(shù)化SQL   
      8. sqlComm.Parameters.Add("@p0", SqlDbType.Int);  
      9. sqlComm.Parameters.Add("@p1", SqlDbType.NVarChar);  
      10. sqlComm.Parameters.Add("@p2", SqlDbType.VarChar);  
      11. sqlComm.CommandType = CommandType.Text;  
      12. sqlComm.Connection = sqlConn;  
      13. sqlConn.Open();  
      14. try  
      15. {  
      16.     //循環(huán)插入100萬條數(shù)據(jù),每次插入10萬條,插入10次。   
      17.     for (int multiply = 0; multiply < 10; multiply++)  
      18.     {  
      19.         for (int count = multiply * 100000; count < (multiply + 1) * 100000; count++)  
      20.         {  
      21.   
      22.             sqlComm.Parameters["@p0"].Value = count;  
      23.             sqlComm.Parameters["@p1"].Value = string.Format("User-{0}", count * multiply);  
      24.             sqlComm.Parameters["@p2"].Value = string.Format("Pwd-{0}", count * multiply);  
      25.             sw.Start();  
      26.             sqlComm.ExecuteNonQuery();  
      27.             sw.Stop();  
      28.         }  
      29.         //每插入10萬條數(shù)據(jù)后,顯示此次插入所用時間   
      30.         Console.WriteLine(string.Format("Elapsed Time is {0} Milliseconds", sw.ElapsedMilliseconds));  
      31.     }  
      32. }  
      33. catch (Exception ex)  
      34. {  
      35.     throw ex;  
      36. }  
      37. finally  
      38. {  
      39.     sqlConn.Close();  
      40. }  
      41.   
      42. Console.ReadLine();  

      耗時圖如下:

      使用Insert語句插入10萬數(shù)據(jù)的耗時圖

      由于運行過慢,才插入10萬條就耗時72390 milliseconds,所以我就手動強行停止了。

       

      下面看一下使用Bulk插入的情況:

      bulk方法主要思想是通過在客戶端把數(shù)據(jù)都緩存在Table中,然后利用SqlBulkCopy一次性把Table中的數(shù)據(jù)插入到數(shù)據(jù)庫

      代碼如下:

      [c-sharp] view plaincopy?
      1. public static void BulkToDB(DataTable dt)  
      2. {  
      3.     SqlConnection sqlConn = new SqlConnection(  
      4.         ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);  
      5.     SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn);  
      6.     bulkCopy.DestinationTableName = "BulkTestTable";  
      7.     bulkCopy.BatchSize = dt.Rows.Count;  
      8.   
      9.     try  
      10.     {  
      11.         sqlConn.Open();  
      12.     if (dt != null && dt.Rows.Count != 0)  
      13.         bulkCopy.WriteToServer(dt);  
      14.     }  
      15.     catch (Exception ex)  
      16.     {  
      17.         throw ex;  
      18.     }  
      19.     finally  
      20.     {  
      21.         sqlConn.Close();  
      22.         if (bulkCopy != null)  
      23.             bulkCopy.Close();  
      24.     }  
      25. }  
      26.   
      27. public static DataTable GetTableSchema()  
      28. {  
      29.     DataTable dt = new DataTable();  
      30.     dt.Columns.AddRange(new DataColumn[]{  
      31.         new DataColumn("Id",typeof(int)),  
      32.         new DataColumn("UserName",typeof(string)),  
      33.     new DataColumn("Pwd",typeof(string))});  
      34.   
      35.     return dt;  
      36. }  
      37.   
      38. static void Main(string[] args)  
      39. {  
      40.     Stopwatch sw = new Stopwatch();  
      41.     for (int multiply = 0; multiply < 10; multiply++)  
      42.     {  
      43.         DataTable dt = Bulk.GetTableSchema();  
      44.         for (int count = multiply * 100000; count < (multiply + 1) * 100000; count++)  
      45.         {  
      46.             DataRow r = dt.NewRow();  
      47.             r[0] = count;  
      48.             r[1] = string.Format("User-{0}", count * multiply);  
      49.             r[2] = string.Format("Pwd-{0}", count * multiply);  
      50.             dt.Rows.Add(r);  
      51.         }  
      52.         sw.Start();  
      53.         Bulk.BulkToDB(dt);  
      54.         sw.Stop();  
      55.         Console.WriteLine(string.Format("Elapsed Time is {0} Milliseconds", sw.ElapsedMilliseconds));  
      56.     }  
      57.   
      58.     Console.ReadLine();  
      59. }  

      耗時圖如下:

      使用Bulk插入100萬數(shù)據(jù)的耗時圖

      可見,使用Bulk后,效率和性能明顯上升。使用Insert插入10萬數(shù)據(jù)耗時72390,而現(xiàn)在使用Bulk插入100萬數(shù)據(jù)才耗時17583。

       

      最后再看看使用表值參數(shù)的效率,會另你大為驚訝的。

       

      表值參數(shù)是SQL Server 2008新特性,簡稱TVPs。對于表值參數(shù)不熟悉的朋友,可以參考最新的book online,我也會另外寫一篇關于表值參數(shù)的博客,不過此次不對表值參數(shù)的概念做過多的介紹。言歸正傳,看代碼:

      [c-sharp] view plaincopy?
      1. public static void TableValuedToDB(DataTable dt)  
      2. {  
      3.     SqlConnection sqlConn = new SqlConnection(  
      4.       ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);  
      5.     const string TSqlStatement =  
      6.      "insert into BulkTestTable (Id,UserName,Pwd)" +  
      7.      " SELECT nc.Id, nc.UserName,nc.Pwd" +  
      8.      " FROM @NewBulkTestTvp AS nc";  
      9.     SqlCommand cmd = new SqlCommand(TSqlStatement, sqlConn);  
      10.     SqlParameter catParam = cmd.Parameters.AddWithValue("@NewBulkTestTvp", dt);  
      11.     catParam.SqlDbType = SqlDbType.Structured;  
      12.     //表值參數(shù)的名字叫BulkUdt,在上面的建立測試環(huán)境的SQL中有。   
      13.     catParam.TypeName = "dbo.BulkUdt";  
      14.     try  
      15.     {  
      16.       sqlConn.Open();  
      17.       if (dt != null && dt.Rows.Count != 0)  
      18.       {  
      19.           cmd.ExecuteNonQuery();  
      20.       }  
      21.     }  
      22.     catch (Exception ex)  
      23.     {  
      24.       throw ex;  
      25.     }  
      26.     finally  
      27.     {  
      28.       sqlConn.Close();  
      29.     }  
      30. }  
      31.   
      32. public static DataTable GetTableSchema()  
      33. {  
      34.     DataTable dt = new DataTable();  
      35.     dt.Columns.AddRange(new DataColumn[]{  
      36.       new DataColumn("Id",typeof(int)),  
      37.       new DataColumn("UserName",typeof(string)),  
      38.       new DataColumn("Pwd",typeof(string))});  
      39.   
      40.     return dt;  
      41. }  
      42.   
      43. static void Main(string[] args)  
      44. {  
      45.     Stopwatch sw = new Stopwatch();  
      46.     for (int multiply = 0; multiply < 10; multiply++)  
      47.     {  
      48.         DataTable dt = TableValued.GetTableSchema();  
      49.         for (int count = multiply * 100000; count < (multiply + 1) * 100000; count++)  
      50.         {          
      51.             DataRow r = dt.NewRow();  
      52.             r[0] = count;  
      53.             r[1] = string.Format("User-{0}", count * multiply);  
      54.             r[2] = string.Format("Pwd-{0}", count * multiply);  
      55.             dt.Rows.Add(r);  
      56.         }  
      57.         sw.Start();  
      58.         TableValued.TableValuedToDB(dt);  
      59.         sw.Stop();  
      60.         Console.WriteLine(string.Format("Elapsed Time is {0} Milliseconds", sw.ElapsedMilliseconds));  
      61.     }  
      62.   
      63.     Console.ReadLine();  
      64. }  

      耗時圖如下:

      使用表值參數(shù)插入100萬數(shù)據(jù)的耗時圖

      比Bulk還快5秒。

        本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多