【问题标题】:How retrieve and display data from a database in a windows form?如何在 Windows 窗体中从数据库中检索和显示数据?
【发布时间】:2013-04-12 18:58:58
【问题描述】:

我正在尝试通过基于特定电子邮件选择记录来在我的 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();
}

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

【问题讨论】:

标签: c# winforms


【解决方案1】:

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

通常你会这样使用它:

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

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

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

【讨论】:

  • @user2273995 它有助于解决您的问题吗? :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
相关资源
最近更新 更多