使用SqlBulkCopy with datatable插入excel记录
本文关键字:excel 记录 插入 datatable SqlBulkCopy with 使用 | 更新日期: 2023-09-27 18:13:35
我试图使用SqlBulkCopy与数据表插入数据到数据库
我有这个代码
string mydemo="my demo record";
DataTable prodSalesData = new DataTable("ProductSalesData");
// Create Column 1: SaleDate
DataColumn dateColumn = new DataColumn();
dateColumn.DataType = Type.GetType("System.String");
dateColumn.ColumnName = "SaleDate";
prodSalesData.Columns.Add(dateColumn);
DataRow dailyProductSalesRow = prodSalesData.NewRow();
dailyProductSalesRow["SaleDate"] = mydemo;
// Create DbDataReader to Data Worksheet
using (OleDbDataReader dr1 = command1.ExecuteReader())
{
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy1 = new SqlBulkCopy(con))
{
bulkCopy1.DestinationTableName = "activity1";
bulkCopy1.ColumnMappings.Add(0, "id");
bulkCopy1.ColumnMappings.Add(1,"name");
bulkCopy1.ColumnMappings.Add(2, "activity1first");
bulkCopy1.ColumnMappings.Add(3, "activity1second");
bulkCopy1.ColumnMappings.Add(4, prodSalesData.Columns.ToString());
bulkCopy1.WriteToServer(dr1);
}
}
这里的4记录来自xcell文件,但我想插入一个外部数据到同一表,我尝试了这么多,但它给了我这个错误
The given ColumnMapping does not match up with any column in the source or destination.
帮忙吗?
谢谢
触发该错误是因为您正在为4个prodSalesData列(按位置)设置映射,但您只有一列。ColumnMappings应该包含从源映射到目标的列,即
bulkCopy1.ColumnMappings.Add("SaleDate", prodSalesData.Columns.ToString());