How to connect to a MS Access file (mdb) using C#?

前端 未结 6 811
迷失自我
迷失自我 2020-11-27 21:24

I\'m trying to connect to a mdb file and I understand that I would need Microsoft.OLEDB.JET.4.0 data provider. Unfortunately, I do not have it installed on the

6条回答
  •  囚心锁ツ
    2020-11-27 21:33

    The simplest way to connect is through an OdbcConnection using code like this

    using System.Data.Odbc;
    
    using(OdbcConnection myConnection = new OdbcConnection())
    {
        myConnection.ConnectionString = myConnectionString;
        myConnection.Open();
    
        //execute queries, etc
    
    }
    

    where myConnectionString is something like this

    myConnectionString = @"Driver={Microsoft Access Driver (*.mdb)};" + 
    "Dbq=C:\mydatabase.mdb;Uid=Admin;Pwd=;
    

    See ConnectionStrings

    In alternative you could create a DSN and then use that DSN in your connection string

    • Open the Control Panel - Administrative Tools - ODBC Data Source Manager
    • Go to the System DSN Page and ADD a new DSN
    • Choose the Microsoft Access Driver (*.mdb) and press END
    • Set the Name of the DSN (choose MyDSN for this example)
    • Select the Database to be used
    • Try the Compact or Recover commands to see if the connection works

    now your connectionString could be written in this way

    myConnectionString = "DSN=myDSN;"
    

提交回复
热议问题