执行OleDbCommand时出错..“必须声明标量变量”@MaxID“。”

private void AddValue(string strValue) { //get the maximum id for Lists first int MaxID = DataOperations.ReturnMaxIDInATable("Lists", connString); int iSqlStatus = 0; string query = "INSERT INTO Lists(ID, ListName, ListValue) VALUES(@MaxID, @ListName, @ListValue)"; MaxID++; OleDbConnection dbConn = new OleDbConnection(connString); OleDbCommand dbComm = new OleDbCommand(); dbComm.Parameters.Clear(); try { dbComm.CommandText = query; dbComm.CommandType = CommandType.Text; OleDbParameter IDParam = new OleDbParameter(); IDParam.ParameterName = "@MaxID"; IDParam.OleDbType = OleDbType.BigInt; IDParam.Value = MaxID; dbComm.Parameters.Add(IDParam); dbComm.Parameters.AddWithValue("@ListName", ListName); dbComm.Parameters.AddWithValue("@ListValue", strValue); dbComm.Connection = dbConn; DataAccess.HandleConnection(dbConn); iSqlStatus = Convert.ToInt16(dbComm.ExecuteNonQuery()); //Now check the status if (iSqlStatus != 0) { //DO your failed messaging here //return false; } else { //Do your success work here //dbComm. //return true; } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error inserting value in " + ListName + "," + strValue); //return false; } finally { DataAccess.HandleConnection(dbConn); } } 

我相信你需要在通过OleDbCommand执行SQL时使用问号作为参数(当SqlCommand使用@时)。 例:

 INSERT INTO Lists (ID, ListName, ListValue) VALUES (?, ?, ?) 

您只需按照它们在SQL中出现的顺序添加参数。

如果在查询开头包含“DECLARE”子句,则可以正常工作:

 string query = "DECLARE @MaxID as bigint, "+ " @ListName as Varchar(100), "+ " @ListValue As Varchar(100) " + " INSERT INTO Lists(ID, ListName, ListValue) " + " VALUES(@MaxID, @ListName, @ListValue)" 

此外,正确的解决方案是将您的驱动程序更改为SQLClient和OracleClient。 建议不要将OleDb用于SQL 2005及更高版本。

以下片段应为:

 IDParam.ParameterName = "MaxID"; IDParam.OleDbType = OleDbType.BigInt; IDParam.Value = MaxID; dbComm.Parameters.Add(IDParam); dbComm.Parameters.AddWithValue("ListName", ListName); dbComm.Parameters.AddWithValue("ListValue", strValue); 

这似乎可以解决问题..

 string query = string.Format("INSERT INTO Lists(ID, ListName, ListValue) VALUES({0}, '{1}', '{2}')", MaxID, ListName, strValue); 

虽然我对它有所保留,就像我需要添加日期值一样?