C#ADO.NET:检查现有索引

时间:2015-01-08 13:06:41

标签: c# ado.net

我有以下代码,如果在表中找不到id,我想显示一条错误消息吗?

private void button4_Click(object sender, EventArgs e)
{
    conn = new MySqlConnection(cs);
    string sql = "select * from question where id=@id;";
    MySqlCommand cmd = new MySqlCommand(sql, conn);
    conn.Open();
    cmd.Prepare();
    cmd.Parameters.AddWithValue("@id", int.Parse(textBox1.Text));
    MySqlDataReader rd = cmd.ExecuteReader();
    string res = "";

    while (rd.Read())
    {
        if (rd.HasRows==true)

        {
            res = string.Format("id={0} pid={1} question={2}", rd.GetInt32(0), rd.GetInt32(1), rd.GetString(2));
            MessageBox.Show("found" + "\n" + res);
        }
        MessageBox.Show(" id not found");


    } 

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要在开始迭代读者之前检查是否有行。

if (rd.HasRows==true)
{
while (rd.Read())
{
// Do something here
}
}
else
{
// Show message here
}