【问题标题】:Data type mismatch in criteria expression(Convert.ToInt32(cmd.ExecuteScalar());)标准表达式中的数据类型不匹配(Convert.ToInt32(cmd.ExecuteScalar());)
【发布时间】:2016-06-02 12:23:33
【问题描述】:

如果用户输入的 ID 与 MS ACCESS DATABASE 中的记录匹配,我正在尝试在数据库的文本框中显示一个名称。 我在 int count = Convert.ToInt32(cmd.ExecuteScalar());

行收到错误 Data type mismatch in criteria expression

以下是我的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 = "";
}

【问题讨论】:

    标签: c# visual-studio ms-access oledb


    【解决方案1】:

    我猜这是因为您将 ID(通常是数值)作为文本字段传递:

    DoctorID='" + TextBox1.Text.Trim() + "'
    

    应该是:

    DoctorID=" + TextBox1.Text.Trim()
    

    另一个问题出现了,因为您很容易受到 SQL 注入的攻击。如果文本框包含1; delete users 怎么办?然后您的整个用户表将是空的。经验教训:使用参数化查询!

    那么你可以将SQL表示为:

    DoctorID= ?
    

    并将参数添加到请求中:

    cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());
    

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 2013-12-23
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多