datatable数据集中的字段与数据库中的字段一一对应
#region 使用SqlBulkCopy将DataTable中的数据批量插入数据库中 /// <summary> /// 使用SqlBulkCopy将DataTable中的数据批量插入数据库中 /// </summary> /// <param name="strTableName">数据库中对应的表名</param> /// <param name="dtData">数据集</param> public static int InsertCopy(this SqlConnection conn, string strTableName, DataTable dtData, DbTransaction transaction = null) { SqlBulkCopy sqlRevdBulkCopy = transaction == null ? new SqlBulkCopy(conn) : new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, (SqlTransaction)transaction); sqlRevdBulkCopy.BulkCopyTimeout = 8000; try { if (conn.State == ConnectionState.Closed) { conn.Open(); } sqlRevdBulkCopy.DestinationTableName = strTableName;//数据库中对应的表名 sqlRevdBulkCopy.NotifyAfter = dtData.Rows.Count;//有几行数据 sqlRevdBulkCopy.WriteToServer(dtData);//数据导入数据库 return dtData.Rows.Count; } catch (Exception ex) { Wathet.Log.Error(ex.ToSimple("DoSql.InsertCopy,表 [" + strTableName + "] 数据搬迁异常 SqlBulkCopyInsert ")); return -1; } finally { sqlRevdBulkCopy.Close(); if (transaction == null && conn.State == ConnectionState.Open) { conn.Close(); } } } #endregion