首页 文章

异常是System.Data.SqlClient.SqlException:'9988'附近的语法不正确[关闭]

提问于
浏览
-9

我的代码如下
protected void Button1_Click(object sender,EventArgs e){SqlConnection con = new SqlConnection(mycon);

**strong text**

        string str = "insert into CustomerHistoryAD(customerId,checkNumber,bank,city,date,amount) values('" + tb_customerID.Text + "','" + tb_CheckNumber.Text + "','" + tb_bank.Text + "','" + tb_city.Text + "','" + tb_date.Text + "','" + tb_Amount.Text + "')";
    sqlq(str);
 lbl0.Text = " DataSaved Successfully ";
 tb_Notification.Text = "Record of Customer ID '"+tb_customerID.Text+"' is Submitted";


}
protected void Button2_Click(object sender, EventArgs e)
{

    string query = "insert into notification(message) values('" + tb_Notification.Text+ "')";
    String mycon = "Data Source=DESKTOP-79IQ2D8; Initial Catalog=ForexMedia; Integrated Security=true";
    SqlConnection con = new SqlConnection(mycon);
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = query;
    cmd.Connection = con;
    cmd.ExecuteNonQuery();
    Label3.Text = "Notification Sent";
    tb_Notification.Text = "";
}

1 回答

  • 2

    您直接从控件中读取的输入参数中必定存在问题 .

    由于SQL注入攻击威胁,不建议这样做 .

    如果您将查询更改为我们的参数(参数查询),我希望此问题将得到解决 .

    以下是如何使用参数的示例 . 请注意,我没有在示例中使用您的代码:

    SqlCommand objSqlCommand = null;
    strSQL = @"INSERT INTO ... (Field1, ...)
                        VALUES 
                        (@param1, ...)";
    objSqlCommand = new SqlCommand(strSQL);
    objSqlCommand.Parameters.Clear();
    objSqlCommand.Parameters.AddWithValue("@param1", yourControl.Text);
    ....
    ....
    objSqlCommand.ExecuteNonQuery();
    objSqlCommand.Dispose();
    

    您应该通过包含 using 块或正确的 try/catch 块来进一步改进此代码 .

    这样,如果输入中有任何SQL查询敏感字符,它将被正确处理并解决问题 . 强烈建议您远离SQL注入攻击 .

相关问题