what
SqlBulkCopy是.NET提供的用來批量插入數據的一個類,特別是將內存中的數據一次性插入到數據庫,目前只能插入到SQL SERVER數據庫,數據源可以是DataTable、IDataReader
why
SqlBulkCopy插入與循環一條條插入相比,性能有巨大提升,數據越多,性能優勢越明顯。
測試結果:一萬條數據,一條條插入要6秒,Bulk只需要0.1秒。理論上插入百萬條記錄也只需要1分鐘以內
how
以下是測試代碼:
string sourceConStr = "Data Source=192.168.1.100;Initial Catalog=A; uid=sa;pwd=sa"; string destConStr = "Data Source=.;Initial Catalog=B; uid=sa;pwd=sa"; DataTable dt = new DataTable(); public Form1() { InitializeComponent(); } PRivate void button3_Click(object sender, EventArgs e) { dt = GetTable(); MessageBox.Show("get finish"); } private void button1_Click(object sender, EventArgs e) { string str = "queue start...! /n"; Stopwatch sw = new Stopwatch(); sw.Start(); CopyData(dt); sw.Stop(); str += "queue cost time is " + sw.ElapsedMilliseconds + "/n"; richTextBox1.Text = str; } private void button2_Click(object sender, EventArgs e) { string str = "bulk start...! /n"; Stopwatch sw = new Stopwatch(); sw.Start(); CopyDataBulk(dt); sw.Stop(); str += "bulk cost time is " + sw.ElapsedMilliseconds + "/n"; richTextBox2.Text = str; } //從數據源獲取要插入的數據 private DataTable GetTable() { DataTable dt = new DataTable(); using (SqlConnection sourceConnection = new SqlConnection(sourceConStr)) { sourceConnection.Open(); SqlCommand cmd = new SqlCommand("SELECT TOP 10000 CName,PersonID,Sex,Age FROM Customer order by cid asc;", sourceConnection); cmd.CommandTimeout = 600000; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); } return dt; } //一條條插入 private void CopyData(DataTable dt) { using (SqlConnection destinationConnection = new SqlConnection(destConStr)) { destinationConnection.Open(); foreach(DataRow reader in dt.Rows) { string sql = "INSERT INTO Customer(Name,PersonID,Sex,Age) VALUES('" + reader["Cname"].ToString() + "','" + reader["PersonID"].ToString() + "','" + reader["Sex"].ToString() + "','" + reader["Age"].ToString() + "')"; SqlCommand cmd = new SqlCommand(sql, destinationConnection); try { int re = cmd.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } //Bulk插入 private void CopyDataBulk(DataTable dt) { using (SqlConnection destinationConnection = new SqlConnection(destConStr)) { destinationConnection.Open(); using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection)) { //寫對應關系。如舊表的CName列的數據,對應新表Name列 bulkCopy.ColumnMappings.Add("CName", "Name"); //設置目標表名 bulkCopy.DestinationTableName = "Customer"; try { bulkCopy.WriteToServer(dt); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { // reader.Close(); } } } }
新聞熱點
疑難解答