Home

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

Sign In or Register to comment.