![](/img/trans.png)
[英]Replacing placeholders in prepared statement OleDbCommand.Parameters
[英]MySQL insert command using prepared statement and placeholders is not working
我建立了一个MySql数据库和一个C#Windows GUI表单,其中包含文本框字段和一个时间选择器,以在数据库中填充一个名为“ job”的表。
我已经在该站点上阅读了一些有关使用准备好的语句来防止sql注入攻击的重要性的文章,并且我尝试在代码中使用此安全功能。 但是,它不起作用。 我是一名网页设计师,但对编程非常陌生。 我在insert命令中尝试了不同的代码变体仍然无法正常工作。 我在此表单上找到的示例涉及将准备好的语句与PHP一起使用,这不是我正在使用的。
我收到以下错误消息:您的SQL语法有错误。 检查手册或您的MySQL服务器版本以获取在'jobTitle,this.dateTimePickerJobLastUpdated')'附近使用的正确语法
有人知道我在做什么错吗,我该如何解决?
这是该表的MySQL语句。
创建表作业(
job_code VARCHAR(6) NOT NULL DEFAULT '',
job_title VARCHAR(30) NOT NULL DEFAULT '',
job_last_update DATE NOT NULL,
PRIMARY KEY (job_code)
)ENGINE = InnoDB CHARSET = utf8;
这是事件处理程序的C#,它将Windows窗体中的数据条目保存到数据库中。
私人void btnSaveJobsTable_Click(object sender,EventArgs e){
String myConnection = @"server=localhost; database=beautyshopdb; username=$$$$; password=$$$$$$";
MySqlConnection Connect = null;
try
{
Connect = new MySqlConnection(myConnection);
Connect.Open(); //open the connection
//This is the mysql command that we will query into the db.
//It uses Prepared statements and the Placeholder is @name.
//Using prepared statements is faster and secure.
String insertQuery = "INSERT INTO beautyshopdb(job) VALUES(@jobCode, @)jobTitle, @lastUpdated)";
MySqlCommand cmdInsertJobsToDataBase = new MySqlCommand(insertQuery, Connect);
cmdInsertJobsToDataBase.Prepare();
//we will bound a value to the placeholder
cmdInsertJobsToDataBase.Parameters.AddWithValue("@jobCode", "this.txtEnterJobCode.Text");
cmdInsertJobsToDataBase.Parameters.AddWithValue("@jobTitle", "this.txtEnterJobTitle.Text");
cmdInsertJobsToDataBase.Parameters.AddWithValue("@lastUpdated", "this.dateTimePickerJobLastUpdated");
cmdInsertJobsToDataBase.ExecuteNonQuery(); //execute the mysql command
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (Connect != null)
{
Connect.Close(); //close the connection
}
}
}
谢谢!
我不是C#开发人员,但这看起来不太正确,我认为您在jobTitle
之前jobTitle
一个括号:
String insertQuery = "INSERT INTO beautyshopdb(job) VALUES(@jobCode, @)jobTitle, @lastUpdated)";
同样,您似乎也将变量引用放在引号内,就好像它们是字符串常量一样。 我希望这些不需要引号。
cmdInsertJobsToDataBase.Parameters.AddWithValue("@jobCode", "this.txtEnterJobCode.Text");
应该:
cmdInsertJobsToDataBase.Parameters.AddWithValue("@jobCode", this.txtEnterJobCode.Text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.