How to connect to and query a MS Access database (MDB and ACCDB)

edited September 2013
This took some digging around and a little bit of trial and error for me to finally get it to work. I've searched high and low for how to connect to a MS Access Database and found very little pieces of instructions and put them all together. This is my first post and I know it's short and to the point and I may update it or post another one with more structure and details at a later date. I hope this helps someone out!

The language the code below is in is C# Statement(s)

image
// to use the ODBC assembly you have to press F4 then click on tab "Additional Namespace Imports"
// in the list of imports add "System.Data.Odbc" and click OK
// you have to escape any slashes "\" in the full path to the database using an additional slash "\\"

string connectionString = ("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\\northwind\\Nwind.mdb;");

// create a connection to the database by giving the connection string to OdbcConnection
using(OdbcConnection myconnection = new OdbcConnection(connectionString)) {
	
	// create an adapter with OdbcDataAdapter to execute your query
	// and provide the query and your OdbcConnection to the database.
	OdbcDataAdapter myadapter = new OdbcDataAdapter("SELECT * FROM Customers", myconnection);
	
	// create an empty dataset (myCustomersDS) to put all the returned results of your query into
	DataSet myCustomersDS = new DataSet();
	
	// using the adapter.fill({empty dataset}, {from what table?}) to fill your empty dataset
	// with the returned records from your query
	myadapter.Fill(myCustomersDS, "Customers");
	
	// now display your records from your dataset in a grid
	myCustomersDS.Dump();
}
image



(¯`·.¸(¯`·.¸ChipGraphics¸.·´¯)¸.·´¯)

Comments

  • You can use the MS Access Data Context Driver
    MSAccessDataContextDriver.lpx
  • Can you help on how to load an MDC file? I have tried the MS Access Data Context Driver, and cannot load MDC file in linqpad.
  • Hi Rabia, the driver is an .lpx file and the access database is a .mdb or .accdb file. -Download the .lpx-file, in LinqPad,
    -click on Add connection,
    -then click on 'view more drivers...'
    -then click on 'browse' and select the .lpx-file
    -the driver is added on the top list-box and ready to use
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!