2017-08-10 220 views
0

相關的this question:我試圖寫一個「插入」循環:我有以下查詢:數據插入循環不起作用

CommandText = "INSERT into sample2Prot(timestp,idq,idz,prot,Lhowmany,Rhowmany) VALUES(@timestp,@idq,@idz,@prot,@Lhowmany,@Rhowmany)"; 

當我執行我的代碼(可剛剛發現下面)我得到以下錯誤:

'@timestp' cannot be handle by SqlParameterCollection. ("timestp" = tableNames[0], of string type)

for (int j = 0; j < tableNames.Count; j++) 

// tableNames contains the name of the columns, tableTypes the types of the columns 
// tableTypes contains 
{ 
    if (tableTypes[j] == "INTEGER") 
    { 
      myCommand3.Parameters.Add("@" + tableNames[j], System.Data.SqlDbType.Int); 
      Console.WriteLine("@" + tableNames[j]); 
    } 
    else 
    { 
      myCommand3.Parameters.Add("@" + tableNames[j], System.Data.SqlDbType.VarChar); 
      Console.WriteLine("@" + tableNames[j]); 
    } 

} 

Console.WriteLine(myCommand3.CommandText); 
for (int f = 0; f < total.Count(); f++) 
{ 
    for (int k = 0; k < tableNames.Count; k++) 
    { 
      myCommand3.Parameters.Clear(); 
      myCommand3.Parameters["@" + tableNames[k]].Value = total[f][k]; 
    } 

    myCommand3.ExecuteNonQuery(); 
} 

有別人的想法?不介意要求更高的精度。

+1

這看起來並不像一個C#的錯誤消息。你能複製並粘貼EXACT和ENTIRE錯誤信息嗎?此外,數據庫中'timestp'列的數據類型是什麼? –

+0

哪種類型是你的myCommand3? SqlCommand的?我猜你可能想嘗試這樣的事情:CommandText =「插入sample2Prot(timestp,idq,idz,prot,Lhowmany,Rhowmany)VALUES(?,?,?,?,?,?)」; – Tyron78

+0

那麼我個人會在執行時檢查所有這些參數的值。然後將它們插入到您的sql語句中,並嘗試直接在服務器上運行它。我也會運行Profiler,看看有什麼東西被髮送到數據庫。有可能是空值導致問題。 – HLGEM

回答

1
for (int f = 0; f < total.Count(); f++) 
{ 
    for (int k = 0; k < tableNames.Count; k++) 
    { 
      myCommand3.Parameters.Clear(); // < ==== PROBLEM is here! 
      // After clearing the Parameters, there is no Parameter "["@" + tableNames[k]]" 
      // hence "SqlParameter mit ParameterName '@timestp' ist nicht in SqlParameterCollection enthalten." 
      // (eng: SqlParameterCollection does not contain SqlParameter with name '@timestp') 
      myCommand3.Parameters["@" + tableNames[k]].Value = total[f][k]; 
    } 

    myCommand3.ExecuteNonQuery(); 
} 

在上面的代碼中,移動Clear()聲明,如下所示:

for (int f = 0; f < total.Count(); f++) 
{ 
    for (int k = 0; k < tableNames.Count; k++) 
    { 
      myCommand3.Parameters["@" + tableNames[k]].Value = total[f][k]; 
    } 
    myCommand3.ExecuteNonQuery(); 
} 
myCommand3.Parameters.Clear();