簡體   English   中英

來自數據源的 String 類型的給定值無法轉換為指定目標列的 int 類型。

[英]The given value of type String from the data source cannot be converted to type int of the specified target column.'

我正在研究一種插入方法,但它給了我 2 個我似乎無法解決的錯誤,我也是一名實習生,在這方面沒有得到足夠的指導,所以這就是我在這里問它的原因。

int werknemerId = 12345; 
int knowhowLenght = knowhowMatches.Count;
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Kantoor", typeof(int)));
dt.Columns.Add(new DataColumn("Taal", typeof(string)));
dt.Columns.Add(new DataColumn("Spreken", typeof(string)));
dt.Columns.Add(new DataColumn("Lezen", typeof(string)));
dt.Columns.Add(new DataColumn("Schrijven", typeof(string)));
dt.Columns.Add(new DataColumn("Talen_op_werknemerID", typeof(int)));
for (int x = 0; x < languageMatches.Count; x++) 
{
    string lang = languageMatches[x];
    string known = knowhowMatches[x];
    dt.Rows.Add(1, new string[] 
    {
        lang, known, known, known
    }, werknemerId);
}
using(SqlConnection Conn = new SqlConnection(connstring)) 
{
    Conn.Open();
    using(SqlBulkCopy bc = new SqlBulkCopy(Conn)) 
    {
        bc.DestinationTableName = "UzkTalen";
        bc.WriteToServer(dt);
        bc.WriteToServer(dt);
    }
}

我不斷收到此異常:

System.InvalidOperationException:“來自數據源的 String 類型的給定值無法轉換為指定目標列的 int 類型。”

這兩個內部異常:

FormatException:無法將參數值從 String 轉換為 Int32。

FormatException:輸入字符串的格式不正確。

如果有人可以幫助我,那就太好了,所以我可以從中學習

我今天遇到了這個問題。 問題是您的表格列順序與 dataTable 的列順序不同。

例如:

如果您的表格如下所示:

在此處輸入圖像描述

那么您的代碼必須如下所示:

table.Columns.Add("Firm", typeof(short));
table.Columns.Add("TigerId", typeof(int));
table.Columns.Add("LogixId", typeof(int));
table.Columns.Add("Code", typeof(string));
table.Columns.Add("TigerItemId", typeof(int));
table.Columns.Add("RegisteredDate", typeof(DateTime));

如果我們將 Code 列的順序(它是字符串)更改為 first,那么批量插入將不起作用。 例如下面的代碼不起作用:

table.Columns.Add("Code", typeof(string)); // It is string    
table.Columns.Add("Firm", typeof(short));
table.Columns.Add("TigerId", typeof(int));
table.Columns.Add("LogixId", typeof(int));
table.Columns.Add("TigerItemId", typeof(int));
table.Columns.Add("RegisteredDate", typeof(DateTime));

批量插入更喜歡列順序,這意味着如果 dataTable 的列順序與上例中的數據庫表不同,那么批量插入將嘗試將 Code 數據插入到 Firm 列中,這將引發異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM