SQL Server 批量插入數據的兩種方法

  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. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章