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

本文关键字:连接 访问 数据库 | 更新日期: 2023-09-27 18:17:37

我有访问数据库文件,其中有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;

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

试试这个代码,

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

您正在动态地构建一个DataGridView并为它设置数据源。这很好,但是接下来要将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);
     }
}

EDIT在下面的注释之后,很明显文件名(TABLES.ACCDB)和表CLIENTS的名称之间有一点混淆。
SELECT语句定义为(基本形式)

 SELECT field_names_list FROM _tablename_
因此,用于检索所有客户端数据的正确语法是
 string sql  = "SELECT * FROM Clients";

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