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

Sushan Ghimire picture Sushan Ghimire · Apr 29, 2012 · Viewed 99.3k times · Source

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 (University) machine. Since, they don't provide that provider, I believe there should be a way around.

How can I connect to the file without Microsoft.OLEDB.JET.4.0 or is there any alternative ?

I have following providers:

Available Ole DB providers

I have tried using OLE DB Provider for Microsoft Directory Services, to which while testing connection, I get 'Test succeeded but some settings were not accepted by the provider'. I took that string and used it anyway and I got ADsDSOObject' failed with no error message available, result code: DB_E_ERRORSINCOMMAND(0x80040E14).

Answer

Steve picture Steve · Apr 29, 2012

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;"