sqlbulkcopy 多表批量保存
Posted 非同凡向
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlbulkcopy 多表批量保存相关的知识,希望对你有一定的参考价值。
/// <summary> /// 批量保存多表 /// </summary> /// <param name="dt1"></param> /// <param name="TableName"></param> /// <returns></returns> public static void SqlBatchCopy(DataTable dt, string TableName,DataTable dt1, string TableName1) { using (SqlTransaction st = Con.BeginTransaction()) { using (SqlBulkCopy copy = new SqlBulkCopy(Con, SqlBulkCopyOptions.Default, st)) { for (int i = 0; i < dt.Columns.Count; i++) { copy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName); } copy.DestinationTableName = TableName; copy.WriteToServer(dt); } using (SqlBulkCopy copy = new SqlBulkCopy(Con, SqlBulkCopyOptions.Default, st)) { for (int i = 0; i < dt1.Columns.Count; i++) { copy.ColumnMappings.Add(dt1.Columns[i].ColumnName, dt1.Columns[i].ColumnName); } copy.DestinationTableName = TableName1; copy.WriteToServer(dt1); } st.Commit(); } }
//简单测试
DataTable tb = new DataTable(); tb.Columns.Add( "Cname1", typeof (string)); DataRow dr = tb.NewRow(); for (int i = 1; i <= 10000; i++) { dr = tb.NewRow(); dr[ "Cname1"] = "测试" + i; tb.Rows.Add(dr); } System.Diagnostics. Stopwatch st = new System.Diagnostics.Stopwatch(); st.Start(); using (System.Data.SqlClient.SqlBulkCopy copy = new System.Data.SqlClient.SqlBulkCopy ("server=.;database=TestA;uid=sa;pwd=sasa")) { copy.ColumnMappings.Add( "Cname1", "Cname" ); copy.DestinationTableName = "TbA"; copy.WriteToServer(tb); } st.Stop(); MessageBox.Show( "新增成功,耗时" + st.ElapsedMilliseconds);
以上是关于sqlbulkcopy 多表批量保存的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 SqlBulkCopy 并通过 Glimpse 跟踪批量插入