如何从Windows窗体中检索和显示数据库中的数据?

时间:2013-04-12 10:37:42

标签: c# winforms

我试图通过选择基于特定电子邮件的记录来在我的Windows窗体上显示数据库内容。

我正在使用以下代码,但它没有检索它

private void editrecordbutton_Click(object sender, EventArgs e)
{
    MyOleDbConnection.Open();
    string query = string.Format("select Email from login where Email='{0}'", editrecordtextBox.Text);
    OleDbCommand vcom1 = new OleDbCommand(query, MyOleDbConnection.vcon);
    OleDbDataReader reader = vcom1.ExecuteReader();
    //int check = vcom1.ExecuteNonQuery();
    string email = (string)reader["Email"];
    if (email == editrecordtextBox.Text)
    {
        if (editrecordtextBox.Text != string.Empty)
        {
            EmailReturn = editrecordtextBox.Text;
            FinalEdit er = new FinalEdit();
            this.Close();
            er.Show();
            MyOleDbConnection.Close();
        }
        else
        {
            MessageBox.Show("No record selected");
        }
    }
    else
    {
        MessageBox.Show("Invalid Email-Id");
    }
    MyOleDbConnection.Close();
}

请帮助我理解它有什么问题,以及我是否以正确的方式看待这种方法。

1 个答案:

答案 0 :(得分:3)

OleDbDataReader有方法Read。只要有可用的数据,Read就会返回。

通常你会像这样使用它:

while(reader.Read())
{
    // work with the current row of data    
}

由于您从未致电Read,因此您不会检索任何数据。您需要至少调用一次Read以将其移动到查询返回的第一行数据。

您的代码的另一个重要问题与SQL Injection有关。您手动创建查询字符串非常危险。您确实需要切换到参数化查询。这是一篇很好的博客文章,解释了如何使用它们:Give me parameterized SQL, or give me death