【问题标题】:Can't find MySql.Data.MySqlClient.MySqlException insert query error找不到 MySql.Data.MySqlClient.MySqlException 插入查询错误
【发布时间】:2021-06-26 02:59:52
【问题描述】:

这是错误信息

MySql.Data.MySqlClient.MySqlException: '你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以了解在第 1 行的 '''')' 附近使用的正确语法

这是我的查询

MySqlCommand cmd = new MySqlCommand("insert into subject(id, code, title, unit) values('" + textBox1.Text + "',''" + textBox2.Text + "',''" + textBox3.Text + "',''" + textBox4.Text + "')", conn);

我已经查看了一个多小时了,我仍然得到这个错误。

【问题讨论】:

  • 我看到你有很多不匹配的单引号。帮自己一个忙,使用参数而不是连接字符串。编写代码更容易,不会让眼睛疲劳计数引号字符,而且它也是一种更安全的方法来防止 SQL 注入漏洞。
  • 您是否检查了执行此行后形成的结果查询是否正确?因为我可以在这里看到+ " ',' ' " +,所以您提供的查询中的单引号不匹配。
  • 嗨@Vince Garcia,建议使用Paramaterized Query,因为这将简化在查询中添加值并防止SQL Injection

标签: c# mysql sql


【解决方案1】:

建议使用Parameterized Query

更新:根据@CodeCaster 对Stop Using AddWithValue() 文章中提到的问题的建议,我将所有AddWithValue() 切换为Add("@Parameter", SqlDbType).Value

MySqlCommand cmd = new MySqlCommand("insert into subject(id, code, title, unit) values(@ID, @Code, @Title, @Unit)", conn);
cmd.Parameters.Add("@ID", SqlDbType.int).Value = textBox1.Text;
cmd.Parameters.Add("@Code", SqlDbType.Varchar, 10).Value = textBox2.Text;
cmd.Parameters.Add("@Title", SqlDbType.NVarchar, 50).Value = textBox3.Text;
cmd.Parameters.Add("@Unit", SqlDbType.Varchar).Value = textBox4.Text;

还要确保您通过SqlDbType 传递的值必须与相应数据库表列的数据类型匹配

使用参数化查询的原因是:

  1. 它简化了传递参数的查询,并使查询变得更具可读性。
  2. 阻止SQL Injection

参考:Prepare MySQL Statement

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多