当我用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();
答案 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;
// ...
}
}