代码如下:
/// <summary>
/// 批量插入(datatable插入数据库)
/// </summary>
/// <param name="dtNumID"></param>
internal static void _SqlBulkCopyData(DataTable dtNumID)
{
string[] str=new string[]{"CommodityID","CardTypeID","Discount"};
SqlBulkCopyData(dtNumID, connectionString, str, "MF_ComPrice");
}
/// <summary>
/// 将DataTable中数据批量插入远程服务器的数据表中
/// </summary>
/// <param name="dt">源数据集</param>
/// <param name="Conn">目标服务器的数据连接字符串</param>
/// <param name="FieldStr">要插入的字段</param>
/// <param name="TableName">目标服务器的表名</param>
internal static void SqlBulkCopyData(DataTable dt, string Conn, string[] FieldStr, String TableName)
{
//使用SqlBulkCopy把内存表DataTable里的数据插入答卷数据表
System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(Conn);
//指定目标数据库的表名
bcp.DestinationTableName = TableName;
//指定源列和目标列
foreach (string field in FieldStr)
{
bcp.ColumnMappings.Add(field, field);
}
//写入数据库表
bcp.WriteToServer(dt);
bcp.Close();
}