![](/img/trans.png)
[英]SQlBulkCopy The given value of type DateTime from the data source cannot be converted to type int of the specified target column
[英]SQL Bulk Copy “The given value of type String from the data source cannot be converted to type datetime of the specified target column” using ASP.NET
我正在研究ASP.NET MVC4項目,我正在嘗試使用SQL批量復制將數據從xlsx文件(Excel 2010文件)導出到我的數據庫。 我的Excel文件只包含2列:第一列包含數字(從1到25),第二列包含字符(連續系列“a,b,c”)
這是我嘗試導出數據的方法,但是我收到錯誤“數據源中String類型的給定值無法轉換為指定目標列的int類型” :
public ActionResult Bulk()
{
string xConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\maarab\Documents\BulkCopy.xlsx;Extended Properties=Excel 12.0;";
using (OleDbConnection connection = new OleDbConnection(xConnStr))
{
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
connection.Open();
string dbConnection = ((EntityConnection)db.Connection).StoreConnection.ConnectionString;
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
using (var bulkCopy = new SqlBulkCopy(dbConnection))
{
bulkCopy.DestinationTableName = "bm_test"
bulkCopy.WriteToServer(dr); //here I got the error
}
}
return RedirectToAction("Index");
}
是什么導致這個錯誤?
如果DataTable
的列順序與數據庫中表定義的列順序不同(當這會導致類型或長度不兼容時),則SqlBulkCopy.WriteToServer(DataTable)
因混淆消息而失敗。 顯然, WriteToServer
方法不映射列名。
我一直在抱怨這個,直到我手動設置訂單,如下所示:
SqlBulkCopy sbc = new SqlBulkCopy(ConnectionString, SqlBulkCopyOptions.UseInternalTransaction);
sbc.DestinationTableName = "agSoilShapes";
sbc.ColumnMappings.Add("Mukey", "Mukey");
sbc.ColumnMappings.Add("Musym", "Musym");
sbc.ColumnMappings.Add("Shapes", "Shapes");
DataTable dt = new DataTable();
dt.Columns.Add("Mukey", typeof(SqlInt32));
dt.Columns.Add("Musym", typeof(SqlString));
dt.Columns.Add("Shapes", typeof(SqlGeometry));
感謝其他人(@subsci)發表評論,引導我走向這個方向:)
我在使用EntityFramework.BulkInsert包時收到了類似的錯誤。 在這種情況下,根本原因是數據庫表列和生成的模型元數據列(數據庫優先)之間的順序不匹配。
DataTable Columns順序和Database表的列順序應該相同。 它更新了表列的順序后起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.