Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# can';找不到MySql.Data.MySqlClient.MySqlException插入查询错误_C#_Mysql_Sql - Fatal编程技术网

C# can';找不到MySql.Data.MySqlClient.MySqlException插入查询错误

C# can';找不到MySql.Data.MySqlClient.MySqlException插入查询错误,c#,mysql,sql,C#,Mysql,Sql,这是错误消息 MySql.Data.MySqlClient.MySqlException: '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 '''')' at line 1' 这是我的问题 MySqlCommand cmd = new MySqlCommand("i

这是错误消息

MySql.Data.MySqlClient.MySqlException: '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 '''')' at line 1'
这是我的问题

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

我已经看了一个多小时了,除了@Kazi修复错误查询的答案之外,我仍然得到这个错误

或者,建议使用

更新:正如@CodeCaster建议的,我将所有
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
传递的值必须与相应数据库表列的数据类型相匹配

使用参数化查询的原因如下:

  • 它简化了传递参数的查询,并使查询更具可读性
  • 阻止

  • 参考资料:

    我发现您有很多不匹配的单引号。帮个忙,使用参数而不是串接字符串。编写代码更容易,而不需要眼睛疲劳计数引号字符,这也是防止SQL注入漏洞的一种更安全的方法。您是否检查了执行此行后生成的查询是否正确?因为我可以看到,'''+这里提供的查询中有不匹配的单引号。Hi@Vince Garcia,建议使用它,因为这将简化在查询中添加值的过程,并防止