如何对包含的联接表使用按ID搜索

时间:2019-01-27 09:47:56

标签: c# ms-access

我试图创建一个由2个单选按钮(名称和ID)指导的搜索框 问题是当我尝试使用ID搜索时,我的代码不起作用

if (rdb22.Checked == true && textBox9.Text.Length != 0)
{
    try
    {
        string query = "SELECT PatientID FROM Patient WHERE PatientID LIKE @PatientID;";

        // create connection and command

        using (OleDbCommand command = new OleDbCommand(query, cn))
        {
            // define parameters and their values by opening connection
            cn.Open();
            command.Parameters.AddWithValue("@PatientID", String.Format("%{0}%", textBox9.Text));
            OleDbDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    // execute SELECT, close connection
                    PatientNum.Text = reader["PatientID"].ToString();
                }
            }
            else
            {
                MessageBox.Show("No record found");
            }
            reader.Close();
            cn.Close();

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error occured: " + ex.Message);
    }
}
else if (rdb11.Checked == true && textBox9.Text.Length != 0)
{
    try
    {
        string query = "SELECT PatientID FROM Patient WHERE FullName LIKE @FullName;";

        // create connection and command

        using (OleDbCommand command = new OleDbCommand(query, cn))
        {
            // define parameters and their values by opening connection
            cn.Open();
            command.Parameters.AddWithValue("@Name", String.Format("%{0}%", textBox9.Text));
            OleDbDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    // execute SELECT, close connection
                    PatientNum.Text = reader["PatientID"].ToString();
                }
            }
            else
            {
                MessageBox.Show("No record found");
            }
            reader.Close();
            cn.Close();

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error occured: " + ex.Message);
    }
}

1 个答案:

答案 0 :(得分:1)

我假设PatientID是您的Patient表上的数字。如果是这样,则无法将LIKE运算符与像%1%这样的模式一起使用。 LIKE运算符主要用于搜索不区分大小写的文本或搜索部分文本。它没有数字的真实含义。

您需要将查询更改为

 string query = "SELECT PatientID FROM Patient WHERE PatientID = @PatientID;";

并使用

添加参数
 command.Parameters.AddWithValue("@PatientID", textBox9.Text);

还请仔细阅读这篇出色的文章:Can we stop using AddWithValue already