/// <summary> /// 将DataTable导入到SQL数据库表中 /// </summary> /// <param name="dt">DataTable 数据源</param> /// <param name="connectString">SQL连接字符串</param> public static void DataTableToSQLServer(DataTable dt, string connectString) { using (SqlConnection conn = new SqlConnection(connectString)) { conn.Open(); //批量数据处理SQL表 SqlBulkCopy bulkCopy = new SqlBulkCopy(conn); try { bulkCopy.DestinationTableName = "test_table";//要插入的SQL表的表名 bulkCopy.BatchSize = dt.Rows.Count; #region Datatable 表列 对应 SQL表的列 bulkCopy.ColumnMappings.Add(0, 0);//映射字段名 DataTable列 ,数据库 对应的列 bulkCopy.ColumnMappings.Add(1, 1); bulkCopy.ColumnMappings.Add(2, 2); bulkCopy.ColumnMappings.Add(3, 3); bulkCopy.ColumnMappings.Add(4, 4); #endregion bulkCopy.WriteToServer(dt); //复制到SQL指定表 MessageBox.Show("插入成功"); } catch (Exception ex) { MessageBox.Show("异常:"+ex); } } }