2013-06-02 45 views
1

我有一個數據網格,我應該將其列值插入到訪問數據庫,但我有問題command.ExecuteNonQuery();數據庫錯誤:「沒有給出一個或多個必需參數的值。」

我的項目沒有完成,只是因爲這個錯誤。這是我的代碼:

for (int i = 0; i < (dataGridFactorRent.Rows.Count) - 1; i++) 
{ 
    string query = 
     @"INSERT INTO tbl_RentFactor([ID],DateNow,customerName, objectName, 
      objectNumber,unitCost,objectCost,paidMoney,restOfMonyy,customerID,DateBack) 
      VALUES ("+ID+",'" + lbldate.Text + "','" + cmdCustomName.Text + "'," + 
       dataGridFactorRent.Rows[i].Cells[1].Value + ", 
       " + dataGridFactorRent.Rows[i].Cells[3].Value + ", 
       " + dataGridFactorRent.Rows[i].Cells[4].Value + ", 
       " + dataGridFactorRent.Rows[i].Cells[5].Value + ", 
       '" + txtPaid.Text + "','" + lblRemained.Text + "', 
       "+customerID+",'"+lbldate.Text+"')"; 

    con.Open(); 
    command.CommandText =query; 
    command.ExecuteNonQuery(); 
    con.Close(); 
+0

在ExecuteNonQuery之前調試並設置斷點並檢查查詢。在數據庫上手動測試它。避免那些可以使用參數的錯誤。 – Damith

回答

1

正如上述意見中的建議,您應該首先更改代碼以使用參數化查詢。這將減輕您對分隔值的需求,並且還會使您的代碼更安全。另外,您應該利用using聲明讓.NET更好地管理資源。

進行這些更改後的代碼看起來會像這樣:

string query = 
    @"INSERT INTO tbl_RentFactor([ID],DateNow,customerName, objectName, 
     objectNumber,unitCost,objectCost,paidMoney,restOfMonyy,customerID,DateBack) 
     VALUES (?,?,?,?,?,?,?,?,?,?,?)"; 
con.Open(); 
for (int i = 0; i < (dataGridFactorRent.Rows.Count) - 1; i++) 
{ 
    using (var command = new OleDbCommand(query, con)); 
    { 
     command.Parameters.AddWithValue("?", ID); 
     command.Parameters.AddWithValue("?", lbldate.Text); 
     command.Parameters.AddWithValue("?", cmdCustomName.Text); 
     command.Parameters.AddWithValue("?", dataGridFactorRent.Rows[i].Cells[1].Value); 
     command.Parameters.AddWithValue("?", dataGridFactorRent.Rows[i].Cells[3].Value); 
     command.Parameters.AddWithValue("?", dataGridFactorRent.Rows[i].Cells[4].Value); 
     command.Parameters.AddWithValue("?", dataGridFactorRent.Rows[i].Cells[5].Value); 
     command.Parameters.AddWithValue("?", txtPaid.Text); 
     command.Parameters.AddWithValue("?", lblRemained.Text); 
     command.Parameters.AddWithValue("?", customerID); 
     command.Parameters.AddWithValue("?", lbldate.Text); 

     command.ExecuteNonQuery(); 
    } 
} 
con.Close(); 

如果你還在做這些修訂後,再收到錯誤仔細檢查的字段名稱在您的INSERT語句。

0

這意味着在表中找不到列(因此Access認爲它是一個參數)。通常你拼錯了一些東西。似乎「restOfMonyy」應該是「restOfMoney」。如果沒有,請調試應用程序並獲取構建的確切字符串,並使用它查詢並查看會發生什麼。

相關問題