我一直在使用这段代码遇到同样模糊的错误:
command.CommandText = "INSERT INTO database (upc, title, description, quantity) VALUES ('"+ upc.Text +"',"+"'"+titlename+"',"+ "'"+descname+"',"+ "'1'"+"), MyConString";
错误是:
{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'database (upc, title, description, quantity) VALUES ('016000165779','Betty Crock' at line 1"}
我是 C# 的新手,正在尝试构建一个使用插入到 mySQL 数据库中的 UPC 代码的程序。
最佳答案
试试这个:
command.CommandText = "INSERT INTO tableName " +
"(upc, title, description, quantity) " +
"VALUES " +
"(@upc, @title, @description, @quantity)";
command.Parameters.AddWithValue("@upc", upc.Text);
command.Parameters.AddWithValue("@title", titlename);
command.Parameters.AddWithValue("@description", descname);
command.Parameters.AddWithValue("@quantity", "1");
注意事项:
- 这修复了你的 SQL injection hole通过使用参数化查询。尤其是在我看到
upc.Text
的地方,这让我觉得您将用户输入连接到您的 SQL 字符串中(非常危险)。 - 我在您的查询中将“数据库”一词更改为“表名”。这是表名的来源,而不是数据库名。
- 我稍微整理了一下你的字符串声明,这样更容易阅读 =)
关于c# - C# mySQL INSERT 语句错误 - "You have an error in your SQL syntax",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9068003/