SqlBulkCopy批量插入数据库
/// <summary> /// 批量插入数据库。 /// </summary> /// <param name="dt">要插入数据库的表数据</param> /// <param name="tablename">表名</param> /// <returns></returns> public static int SqlBulkCopy(DataTable dt, string tablename) { int result = 0; SqlBulkCopy bulkCopy = null; try { using (SqlConnection conn = new SqlConnection(Const.ERPDBSqlConnentionString)) { conn.Open(); bulkCopy = new SqlBulkCopy(conn); bulkCopy.DestinationTableName = tablename; bulkCopy.BatchSize = dt.Rows.Count; foreach (DataColumn dc in dt.Columns) { bulkCopy.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);//将table中的列与数据库表这的列一一对应 } if (dt != null && dt.Rows.Count > 0) { bulkCopy.WriteToServer(dt); result = 1; } } } catch (Exception ex) { WriteFile("执行插入动作后SqlBulkCopy:(" + DateTime.Now.ToString() + ") " + ex.ToString()); } finally { if (bulkCopy != null) { bulkCopy.Close(); } } return result; }