如果用户输入的ID与MS ACCESS DATABASE中的记录匹配,我试图在数据库的文本框中显示名称。
我在第int count = Convert.ToInt32(cmd.ExecuteScalar());
行
以下是我的aspx.cs代码 -
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
答案 0 :(得分:1)
我想这是因为你传入ID(通常是数值)作为文本字段:
DoctorID='" + TextBox1.Text.Trim() + "'
应该是:
DoctorID=" + TextBox1.Text.Trim()
出现了另一个问题,因为您很容易受到SQL注入攻击。如果文本框包含1; delete users
怎么办?然后您的整个用户表将为空。吸取的教训是:使用参数化查询!
然后您可以将SQL表达为:
DoctorID= ?
并将参数添加到请求中:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());