尝试插入 MS Access 数据库时出错

Error when trying to insert into MS Access Database

我正在开发一个使用关系数据库的程序。我试图以一种特定的形式将新产品信息插入数据库。

using System.Data.OleDb;

当我尝试保存新产品时,运行此代码...

connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "insert into Products (ProductName,ProductSKU,RP,WP,Stock,FPS,Ammo,MagazineCap,HopUp,Range,Brand,Colour,Action,Features) values('" + txt_ProductName.Text + "','" + txt_SKU.Text + "'," + txt_RP.Text + "," + txt_WP.Text + "," + numericUpDown_Inventory.Value + "," + cobo_FPS.Text + ",'" + cobo_Ammo.Text + "'," + cobo_MagazineCap.Text + ",'" + cobo_HopUp.Text + "'," + cobo_Range.Text + ",'" + cobo_Brand.Text + "','" + cobo_Colour.Text + "','" + cobo_Action.Text + "','" + txt_Features.Text + "')";
//Action field currently causes an error
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
connection.Close();

...并抛出错误

"Error System.Data.OleDb.OleDbException (0x80040E14): Syntax error in INSERT INTO statement."

(然后是一堆我认为不重要的东西)

对于巨大的 SQL 查询表示歉意。我在我的程序的其他几个地方使用完全相同的方法使用插入 SQL 查询,它们都工作得很好。然而,这个例子导致了这个错误。通过 "commenting out" 我的 SQL 查询的各个部分的繁琐过程,我发现错误出在 "Action" 字段。我已检查我的数据库中的数据类型是否正确,并且我正在使用 '' 标点包围要插入到数据库中的文本字符串。

我想我已经检查了所有内容,但为什么我仍然收到此错误?

非常感谢,如果需要更多信息,请告诉我 ;)

Action是一个reserved keyword in OLE DB Provider. You need to use it with square brackets like [Action]. As a best practice,改成非保留

但更重要

你应该总是使用 parameterized queries. This kind of string concatenations are open for SQL Injection 攻击。

还可以使用 using statement 自动处理 OleDbConnectionOleDbCommand,而不是手动调用 .Close() 方法。