[英]Debug “Syntax error in INSERT INTO statement” in C# when submitting data to Access Database using OleDbConnection
I'm diving head first into both C# and Access databases. 我首先进入C#和Access数据库。 This is all brand new to me, so I have a small test database set up to work with a small template. 这对我来说是全新的,因此我建立了一个小型测试数据库以使用小型模板。 I'm trying to figure out why I keep getting a syntax error that is triggered by the ExecuteNonQuery() method. 我试图弄清楚为什么我总是收到由ExecuteNonQuery()方法触发的语法错误。 Any help and insight would be appreciated. 任何帮助和见解将不胜感激。
Edit: SOLVED: This is the working code for this situation. 编辑:解决:这是这种情况的工作代码。 All help was greatly appreciated! 感谢所有帮助!
public void addToDb()
{
String first = "John";
String last = "Doe";
String testPath = GVar.TEST_FILEPATH + GVar.TEST_DATABASE;
String strCommand = "INSERT INTO ID ([First], [Last]) Values(@First, @Last)";
OleDbConnection dbTest = null;
OleDbCommand cmd = null;
try
{
dbTest = new OleDbConnection(GVar.OLE_DB_WRITE + testPath);
dbTest.Open();
cmd = new OleDbCommand(strCommand, dbTest);
cmd.Parameters.AddWithValue("@First", first);
cmd.Parameters.AddWithValue("@Last", last);
cmd.ExecuteNonQuery();
Console.WriteLine("Data Added");
}
catch (Exception ex)
{
Console.WriteLine("Db Test: " + ex.Message);
}
dbTest.Close();
}
From OleDbCommand.Parameters
property 从OleDbCommand.Parameters
属性
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. 当CommandType设置为Text时,OLE DB .NET Provider不支持将命名参数传递给SQL语句或OleDbCommand调用的存储过程的命名参数。 In this case, the question mark (?) placeholder must be used. 在这种情况下,必须使用问号(?)占位符。 For example: 例如:
SELECT * FROM Customers WHERE CustomerID = ? 在客户ID =?的情况下从客户中选择*
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text. 因此,将OleDbParameter对象添加到OleDbParameterCollection的顺序必须直接对应于命令文本中参数的问号占位符的位置。
I don't see anything wrong in your INSERT
statement other than this. 除此以外,我在您的INSERT
语句中没有看到任何错误。
cmd.CommandText = "INSERT INTO Identity ([First],[Last]) VALUES(?, ?)";
cmd.Parameters.AddWithValue("@First", first);
cmd.Parameters.AddWithValue("@Last", last);
cmd.ExecuteNonQuery();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.