使用mysql插入数据时出现语法错误
本文关键字:语法 错误 mysql 插入 数据 使用 | 更新日期: 2023-09-27 18:25:32
错误:
"s"附近的语法不正确。字符字符串");"后未闭合的引号。
代码:
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(global::CIMT.Properties.Settings.Default.Database2ConnectionString);
try
{
string sql = "INSERT INTO Students(Student_Id,First_Name,Last_Name,Fathers_Name,DOB,Mobile,Address,Post_Code) VALUES('"+this.txtId.Text+"','"+this.txtFName.Text+"','"+this.txtLName.Text+"','"+this.txtFaName.Text+"','"+this.txtDOB.Text+"','"+this.txtMob.Text+"','"+this.txtAddress.Text+"','"+this.txtPostCode.Text+ "');";
SqlCommand exesql = new SqlCommand(sql, cn);
cn.Open();
exesql.ExecuteNonQuery();
MessageBox.Show("Add new record done !!" , "Message" , MessageBoxButtons.OK , MessageBoxIcon.Information);
this.studentsTableAdapter.Fill(this.database2DataSet.Students);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message , "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
cn.Close();
}
}
像注释中告诉你的那样使用参数化查询,不仅可以避免错误,还可以帮助你避免SQL注入。
private void btnAdd_Click(object sender, EventArgs e)
{
var cnString = global::CIMT.Properties.Settings.Default.Database2ConnectionString;
using (SqlConnection cn = new SqlConnection(cnString))
{
try
{
cn.Open();
using (var exesql = new SqlCommand(
@"INSERT INTO Students(Student_Id
,First_Name
,Last_Name
,Fathers_Name
,DOB
,Mobile
,Address
,Post_Code)
VALUES(@Student_Id
,@First_Name
,@Last_Name
,@Fathers_Name
,@DOB
,@Mobile
,@Address
,@Post_Code);",
cn))
{
exesql.Parameters.AddWithValue("@Student_Id", this.txtId.Text);
exesql.Parameters.AddWithValue("@First_Name", this.txtFName.Text);
exesql.Parameters.AddWithValue("@Last_Name",this.txtLName.Text );
exesql.Parameters.AddWithValue("@Fathers_Name", this.txtFaName.Text);
exesql.Parameters.AddWithValue("@DOB", this.txtDOB.Text);
exesql.Parameters.AddWithValue("@Mobile", this.txtMob.Text);
exesql.Parameters.AddWithValue("@Address", this.txtAddress.Text);
exesql.Parameters.AddWithValue("@Post_Code", this.txtPostCode.Text);
exesql.ExecuteNonQuery();
MessageBox.Show("Add new record done !!" , "Message" , MessageBoxButtons.OK
, MessageBoxIcon.Information);
this.studentsTableAdapter.Fill(this.database2DataSet.Students);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message , "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
阅读SqlParameter类