访问数据库文件中的数据
本文关键字:数据 文件 数据库 访问 | 更新日期: 2023-09-27 18:00:47
我不确定,但我无法获得要在文本框中显示的数据。这是我迄今为止写的代码。任何帮助都会很棒。盒子里什么都没有,但在做测试时,我收到了消息框。有什么地方我做得不对吗?如果需要,我可以提供访问文件。但它只有五个字段有数据
DataSet DataSet1; //use to put data in form
System.Data.OleDb.OleDbDataAdapter dataadapter;
private void Breed_Load(object sender, EventArgs e)
{
dbconnect = new System.Data.OleDb.OleDbConnection();//database connection variable
DataSet1 = new DataSet(); //variable to help get info from DB
dbconnect.ConnectionString = "PROVIDER= Microsoft.Jet.OLEDB.4.0; Data Source=C:/Pets.mdb"; //location of DB to open
dbconnect.Open(); //open command for DB
string sql = "SELECT * From tblPets"; //sql string to select all records from the table pets
dataadapter = new System.Data.OleDb.OleDbDataAdapter(sql, dbconnect); // pulls the records from sql command
MessageBox.Show("Database is Open");
dataadapter.Fill(DataSet1, "Pets"); // used the database to fill in the form.
NavRecords(); //calls NavRecords Method
dbconnect.Close();
MessageBox.Show("Database is Closed");
dbconnect.Dispose();
}
private void NavRecords()
{
DataRow DBrow = DataSet1.Tables["Pets"].Rows[0];
//PetNametextBox.Text = DBrow.ItemArray.GetValue(1).ToString(); //puts data in textbox
TypeofPettextBox.Text = DBrow.ItemArray.GetValue(1).ToString();//puts data in textbox
PetWeighttextBox.Text = DBrow.ItemArray.GetValue(2).ToString();//puts data in textbox
ShotsUpdatedtextBox.Text = DBrow.ItemArray.GetValue(3).ToString();//puts data in textbox
AdoptabletextBox.Text = DBrow.ItemArray.GetValue(4).ToString();//puts data in textbox
BreedtextBox.Text = DBrow.ItemArray.GetValue(5).ToString();//puts data in textbox
}
从Access数据库中获取数据相当简单。这里有一个例子:
public static DataTable GetBySQLStatement(string SQLText)
{
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:''Pets.MDB";
System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection();
Conn.ConnectionString = ConnectionString;
cmd.CommandType = CommandType.Text;
cmd.Connection = Conn;
cmd.CommandText = SQLText;
DataSet ds;
System.Data.OleDb.OleDbDataAdapter da;
DataTable Table = null;
Conn.Open();
da = new System.Data.OleDb.OleDbDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0)
Table = ds.Tables[0];
Conn.Close();
return Table;
}
你这样调用这个函数:
DataTable dt = GetBySQLStatement("SELECT * FROM tblPets");
if (dt != null) {
// If all goes well, execution should get to this line and
// You can pull your data from dt, like dt[0][0]
}
唯一需要注意的是,由于没有64位Jet驱动程序,因此必须将此代码编译为32位应用程序。默认情况下,Visual Studio将作为32位和64位的混合程序进行编译。更改项目设置中的选项以确保其仅为32位。