当我的插入数据是字符串时,无效的列名称,当我使用int它工作正常

时间:2016-01-22 15:13:27

标签: c#-4.0

当我用EmerPacienti替换PatientId时,它运行正常,为什么会这样?

if (DropDownList3.SelectedItem.Value == "In-Pacient")
{
    SqlDataAdapter Da = new SqlDataAdapter("select * from Ipacient where EmerPacienti=" + TextBox11.Text + "", cn);
    //SqlCommandBuilder Cmd = new SqlCommandBuilder(Da);
    DataSet Ds = new DataSet();
    Da.Fill(Ds, "Ipacient");
    GridView1.DataSource = Ds.Tables[0];
    GridView1.DataBind();

1 个答案:

答案 0 :(得分:1)

使用sql参数来阻止sql注入,然后你也不需要将它包装在文本列所需的撇号中。所以这要好得多:

using (var cn = new SqlConnection("insert connection string"))
using(var da = new SqlDataAdapter("select * from Ipacient where EmerPacienti=@EmerPacienti", cn))
{
    da.SelectCommand.Parameters.Add("@EmerPacienti", SqlDbType.VarChar).Value = TextBox11.Text;
    DataTable table = new DataTable();
    da.Fill(table);
    GridView1.DataSource = table;
    GridView1.DataBind();
}

如果是int - 值使用int.Parse / int.TryParse

using (var cn = new SqlConnection("insert connection string"))
using(var da = new SqlDataAdapter("select * from Ipacient where PatientId=@PatientId", cn))
{
    int patientId;
    if (int.TryParse(TextBox11.Text, out patientId))
    {
        da.SelectCommand.Parameters.Add("@PatientId", SqlDbType.Int).Value = patientId;
        // ...
    }
}