C#mySQL INSERT语句出错 - “您的SQL语法出错”

时间:2012-01-30 17:25:18

标签: c# mysql insert mysql-error-1064

我一直在使用此代码获得同样的模糊错误:

command.CommandText = "INSERT INTO database (upc, title, description, quantity) VALUES ('"+ upc.Text +"',"+"'"+titlename+"',"+ "'"+descname+"',"+ "'1'"+"), MyConString";

错误是:

  

{“您的SQL语法有错误;请查看手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'数据库(upc,title,description,quantity)VALUES   ('016000165779','Betty Crock'在第1行“}

我是C#的新手并尝试构建一个使用UPC代码插入mySQL数据库的程序。

5 个答案:

答案 0 :(得分:4)

试试这个:

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字符串(非常危险)。
  • 我在您的查询中将“database”更改为“tableName”。这就是表的名称,而不是数据库名称。
  • 我把你的字符串声明加了一点,以便更容易阅读=)

答案 1 :(得分:3)

database可能是保留字。尝试用反引号转义它:

INSERT INTO `database` ...

我也不确定为什么, MyConString部分在查询本身内部,但我不是C#专家。

答案 2 :(得分:3)

为什么在查询结尾处有“,MyConString”?这看起来很奇怪。

此外,database可能不是的名称。

答案 3 :(得分:1)

数据库是mysql中的关键字,尝试给出描述性名称,这样有助于理解。并使用参数化查询来避免sql注入SqlInjections

这是mysql关键字列表:MySql Reserved keywords,以后尽量避免使用关键字。

    command.CommandText = "INSERT INTO [database] (upc, title, description, quantity) VALUES (@upc,@title ... ) 
command.Parameters.AddWithValue("@upc","upcValue");
command.Parameters.AddWithValue("@title","titleValue");

答案 4 :(得分:0)

我认为你在昏迷前最后错过了双引号:

“+”)",MyConString“;