' ='附近的语法不正确

时间:2016-06-14 12:03:33

标签: c# winforms


我该如何纠正这个错误?这一行出错:readK.Fill(dt1);。谢谢!

private void comboBox5_SelectedValueChanged(object sender, EventArgs e)
{
    comboBox6.SelectedValueChanged -= comboBox6_SelectedValueChanged;
    DataTable dt1 = new DataTable();
    BindingSource bd = new BindingSource();
    conn.Open();
    bd.DataSource = dt1;
    SqlCommand selK = new SqlCommand("Select * from Kafedra where id_fcultet=" + comboBox5.SelectedValue, conn);
    SqlDataAdapter readK = new SqlDataAdapter(selK);
    readK.Fill(dt1);
    comboBox6.DataSource = bd;
    comboBox6.DisplayMember = "name";
    comboBox6.SelectedIndex = -1;
    comboBox6.ValueMember = "id_kafedra";
    textBox2.Text = i + comboBox5.SelectedValue;
    conn.Close();
    comboBox6.SelectedValueChanged += comboBox6_SelectedValueChanged;
}

2 个答案:

答案 0 :(得分:3)

解决此问题的最佳方法是使用sql-parameters,这也将修复可能的sql注入:

SqlCommand selK = new SqlCommand("Select * from Kafedra where id_facultet=@id_facultet, conn);
sqlK.Parameters.Add("@id_facultet", SqlDbType.Int).Value = int.Parse(comboBox5.SelectedValue.ToString());

如果此代码导致FormatException comboBox5.SelectedValue不是整数。如果它首先是一个整数(使用调试器),你也可以使用强制转换:... .Value = (int)comboBox5.SelectedValue;

答案 1 :(得分:1)

用于构建查询的字符串连接方法将为SQL注入打开一扇门,因此我强烈建议您使用参数化查询来避免SQL注入。以下是执行相同操作的示例:

 SqlCommand selK = new SqlCommand("Select * from Kafedra where id_facultet=@someID", conn);
 selK.Parameters.Add("@someID",SqlDbType.Varchar).value= comboBox5.SelectedValue;

您可以根据表格中特定字段的类型选择SqlDbType.Varchar