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,建议使用它,因为这将简化在查询中添加值的过程,并防止