如何在c#中连接访问数据库

时间:2013-06-10 12:26:31

标签: c# .net ado.net

我有访问数据库文件,其中包含7个表,但我不知道如何连接并显示所有表,如果有人可以帮助我?

这是我的代码,但它没有显示任何内容

private void button1_Click(object sender, EventArgs e)
{
    OleDbConnection conn = new OleDbConnection();
    String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
    string sql  = "SELECT Clients  FROM Tables";
    conn.ConnectionString = connection;
    conn.Open();
    DataSet ds = new DataSet();
    DataGridView dataGridView1 = new DataGridView();
    BindingSource bSource = new BindingSource();
    OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn);
    adapter.Fill(ds);
    //conn.Close();                               
    dataGridView1.DataSource = ds;

2 个答案:

答案 0 :(得分:15)

试试这段代码,

public void ConnectToAccess()
{
    System.Data.OleDb.OleDbConnection conn = new 
        System.Data.OleDb.OleDbConnection();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
        @"Data source= C:\Documents and Settings\username\" +
        @"My Documents\AccessFile.mdb";
    try
    {
        conn.Open();
        // Insert code to process data.
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }
}

http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx

答案 1 :(得分:4)

您正在构建DataGridView并为其设置DataSource。这很好,但是你是否将DataGridView添加到托管表单的Controls集合中?

this.Controls.Add(dataGridView1);

顺便说一句,代码有点混乱

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

编辑在下面的评论之后,很明显文件名(TABLES.ACCDB)与表CLIENTS的名称之间存在一些混淆。
The SELECT statement被定义为(基本形式)为

 SELECT field_names_list FROM _tablename_

所以用于检索所有客户端数据的正确语法是

 string sql  = "SELECT * FROM Clients";

其中*表示 - >表中的所有字段