码迷,mamicode.com
首页 > 数据库 > 详细

sqlbulkcopy 多表批量保存

时间:2017-09-27 18:52:52      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:efault   mil   tab   turn   ping   write   dia   nsa   sage   

        
     /// <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 多表批量保存

标签:efault   mil   tab   turn   ping   write   dia   nsa   sage   

原文地址:http://www.cnblogs.com/xiang-wei/p/7603037.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!