【发布时间】:2014-10-05 08:46:34
【问题描述】:
错误:
“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 注入的攻击。为了我们的缘故,请参数化您的查询。这也几乎肯定会修复这个语法错误。
-
您是否将输入输入为 "hello's world" ,然后,它不会被转义,并且您会收到错误,因此如上所述(SQL 注入),最好使用参数化查询。