在c#中显示访问数据库中的单行

时间:2013-12-08 17:33:50

标签: c# ms-access-2010

我有一个项目,其中一部分要求用户输入患者的ID以显示他/她的详细信息 这是我的代码

        sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=hospital database.accdb";
        dbConn = new OleDbConnection(sConnection);
        dbConn.Open();
        sql = "SELECT * FROM Patients";
        dbCmd = new OleDbCommand();
        dbCmd.CommandText = sql;
        dbCmd.Connection = dbConn;

        dbReader = dbCmd.ExecuteReader();


        listBox1.Items.Clear();




        if (dbReader.HasRows)
        {
            while (dbReader.Read())
            {

                if (dbReader["PatientID"] != DBNull.Value)
                {

                    int anInteger;
                    anInteger = Convert.ToInt32(textBox7.Text);
                    anInteger = int.Parse(textBox7.Text);

                    if (anInteger == 101)
                    {

                    }

                }


            }
        }

在IF语句中,我不知道该写什么,只在这个ID上显示在病人的行上

请帮助!!

4 个答案:

答案 0 :(得分:1)

不是选择所有行,而是使用参数过滤要查找的一行并按如下方式修改SQL语句更有效。

    sql = "SELECT * FROM Patients WHERE PatientID = [pID]";
    dbCmd = new OleDbCommand();
    dbCmd.CommandText = sql;
    dbCmd.Connection = dbConn;
    dbcmd.Parameters.AddWithValue("pID", 101);
    dbReader = dbCmd.ExecuteReader();

我还建议调查“使用”条款。这是一个SO example

答案 1 :(得分:1)

  sql = "SELECT Count(*) FROM Patients WHERE PatientID = @PID";
    dbCmd = new OleDbCommand();
    dbCmd.CommandText = sql;
    dbCmd.Connection = dbConn;
    dbcmd.Parameters.AddWithValue("@PID", 101);
    Int32 Cnt = dbCmd.ExecuteScalar();
if ( Cnt > 0)
{
// Do Something
}
else  { // Do something} 

答案 2 :(得分:0)

你必须使用变量来确保找到你的ID,并且break;一旦找到它就退出你的循环

if (dbReader.HasRows)
        {
           bool found  = false;  
            while (dbReader.Read())
            {

                if (dbReader["PatientID"] != DBNull.Value)
                {

                    int anInteger;
                    anInteger = Convert.ToInt32(textBox7.Text);
                    anInteger = int.Parse(textBox7.Text);

                    if (anInteger == 101)
                    {
                        found = true ;  Break; 

                    }

                }


            }
        }

答案 3 :(得分:0)

    int anInteger = Convert.ToInt32(textBox7.Text);        
    sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=hospital database.accdb";
    dbConn = new OleDbConnection(sConnection);
    dbConn.Open();
    sql = "SELECT * FROM Patients where PatientID=@PatientID";
    dbCmd = new OleDbCommand();
    dbCmd.CommandText = sql;
    dbCmd.Parameters.AddWithValue("@PatientID",anInteger);
    dbCmd.Connection = dbConn;

    dbReader = dbCmd.ExecuteReader();


    listBox1.Items.Clear();
    while (dbReader.Read())
    {
       //now display the reader values here : sample
       //TextBox1.Text=dbReader["name"].ToString();
    }