来自访问db文件的数据

时间:2011-06-29 19:12:12

标签: c# database ms-access

我不确定,但我无法在文本框中显示数据。这是我到目前为止编写的代码。任何帮助都会很棒。方框中没有任何内容,但在进行测试时我收到了消息框。我有什么不对的吗?如果需要,我可以提供访问文件。但是只有五个字段包含数据。

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
}

1 个答案:

答案 0 :(得分:2)

从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]
}

要知道的唯一“问题”是,此代码必须编译为32位应用程序,因为没有64位Jet驱动程序。默认情况下,Visual Studio将编译为混合的32位和64位程序。更改项目设置中的选项以确保其仅为32位。