当前位置:Gxlcms > 数据库问题 > sqlbulkcopy 多表批量保存

sqlbulkcopy 多表批量保存

时间:2021-07-01 10:21:17 帮助过:5人阅读

<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   

人气教程排行