我创建了一个C#应用程序并集成了一个Access DB(带有3个填充表)。
现在我尝试从Access DB表中获取数据以在TextBox中显示它,但没有任何内容可见。
提前谢谢。
更新:命名空间 - > using System.Data.OleDb;
以下是代码:
OleDbDataReader myReader;
OleDbConnection myCon;
OleDbCommand myQuery;
public Form1()
{
InitializeComponent();
myCon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\UserName\\Desktop\\MyClubAdministration\\MyClubAdministrationDB.accdb;Persist Security Info=False;");
myCon.Open();
myQuery = new OleDbCommand("select * from Lid, Lidgeld, Lidmaatschap", myCon);
myReader = myQuery.ExecuteReader();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = myReader.GetInt32(0).ToString();
}
答案 0 :(得分:1)
你需要在OleDBDataReader上的GetInt32之前阅读
private void Form1_Load(object sender, EventArgs e)
{
myReader.Read();
textBox1.Text = myReader.GetInt32(0).ToString();
}
但是这段代码非常容易出错 尝试在私有方法中隔离数据库操作,只从一个点调用,而不在构造函数和form_load之间进行拆分。
private void ReadFromDB()
{
using(OleDbConnection myCon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\UserName\\Desktop\\MyClubAdministration\\MyClubAdministrationDB.accdb;Persist Security Info=False;"))
{
myCon.Open();
OleDbCommand myQuery = new OleDbCommand("select * from Lid, Lidgeld, Lidmaatschap", myCon);
OleDbDataReader myReader = myQuery.ExecuteReader();
if(myReader.HasRows)
{
myReader.Read();
textBox1.Text = myReader.GetInt32(0).ToString();
}
}
}
在InitializeComponent();
之后调用该方法作为旁注,我将避免数据库操作的全局变量。通过连接池,打开和重新打开连接的性能成本非常低,而清理的复杂性呈指数级增长。
答案 1 :(得分:1)
ExecuteReader()
类的OleDbCommand
方法返回类OleDbDataReader
的对象。当OleDbDataReader
对象首次返回给您时,它处于“未定位”状态 - 也就是说,它不会定位到数据集中的任何记录。您必须调用Read()
ob对象将其定位到集合中的下一条记录。您的Load()
方法应如下所示:
private void Form1_Load(object sender, EventArgs e)
{
if(myReader.HasRows == true)
{
myReader.Read();
textBox1.Text = myReader.GetInt32(0).ToString();
}
}
对HasRows
的{{1}}属性的调用是为了确保在执行定位之前数据集中实际存在记录。
为了更加小心,您可以在尝试使用之前检查您感兴趣的数据库OleDbDataReader
字段:
null