c# - C# mySQL INSERT 语句错误 - "You have an error in your SQL syntax"

标签 c# mysql insert mysql-error-1064

我一直在使用这段代码遇到同样模糊的错误:

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/

相关文章:

c# - 在 C# WPF 中使用 MySQL 数据库使 Datagrid 可搜索

php - mysqli 为 INSERT 查询返回 true,未插入行

php - SQL INSERT INTO 不起作用

c# - 有没有办法在Unity中使用不同的脚本函数而不使用gameObject?

c# - 我在 Unity 中使用了 C# 秒表类,但它只返回 00 :00:00

c# - 已启用的组合框控件在 Windows 10 中看起来已禁用?

c# - 这个错误 : System. Runtime.InteropServices.COMException 是什么?

mysql - 追加连接

mysql-Calpont 未启动

mysql - 使用唯一值从一个表插入到另一个表