我從我的代碼收到以下錯誤:發生來自的ExecuteScalar上的OleDbCommand鑄造在C#
以下錯誤:
System.Data.OleDb.OleDbException(0x80040E07):在數據類型不匹配標準表達。 在System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult小時) 在System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult在System.Data.OleDb.OleDbCommand.ExecuteCommandText(tagDBPARAMS dbParams,對象&的ExecuteReuslt) (對象&的ExecuteReuslt) 在System.Data.OleDb.OleDbCommand.ExecuteCommand(的CommandBehavior行爲,對象&的ExecuteReuslt) 在System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(的CommandBehavior行爲,字符串方法) 在System.Data.OleDb.OleDbCommand.ExecuteScalar() at NJDataExtractExceltoAccess.Form1.FindAcctId(String x,OleDbConnection y)in C:\ Path \ Form1.cs:line 158
private int FindAcctId(string x, OleDbConnection y)
{
//try
//{
string[] ID = x.Split('-');
string lookup = "Select Id from tbl_name where Col1 = '110' And Col2 = " + ID[0] + "And Col3 = " + ID[1] + "And Col4 = " + ID[2] + "And Col5 = " + ID[3] + "And Col6 = " + ID[4] + "And Col7 = " + ID[5] + "And Col7 = " + ID[6];
OleDbCommand cmd = new OleDbCommand(lookup, y);
Int32 result = (Int32)cmd.ExecuteScalar(); // line 158
Return_val = (int)result;
//}
//catch (Exception Er)
//{
// OutputBox.Text = "The following errors occurred: " + Er;
//}
return Return_val;
}
微軟網頁這樣說:
典型的ExecuteScalar查詢可以被格式化爲下面的C#示例:
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();
我也曾嘗試:
int result = (int)cmd.ExecuteScalar();
和
object result = cmd.ExecuteScalar();
但我在同一行收到相同的數據類型錯誤。如何在OleDbCommand
對象(連接和插入字符串工作)上從ExecuteScalar()
投射?
除此之外,您還應該使用參數化查詢的事實(http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters.aspx),是對所有列數字?如果他們是varchar,你需要在每個單引號。 – sgeddes
您在每個「And ColXXX =」字符串段的開始部分缺少空格,因此最終會出現可能格式不正確的查詢,即「Col2 = 1和Col3 = 2和Col4 = ...」等 –