How to Read MDB for ODBC
Using Open Database Connectivity (ODBC) to read an MDB file can be accomplished using different programming languages such as Visual C#. MDB is the file format for a Microsoft Access 2007 database or older. ODBC is one of the oldest technologies to access relational databases such as MDB files. You can use the “OdbcConnection” class to open the database connection and the “OdbcCommand” class to query the database. The “OdbcDataReader” class is used to read the results from the command you sent to the database.
Instructions
-
-
1
Launch Microsoft Visual Studio, click “New Project” and expand “Other Languages.” Expand “Visual C#” and double-click “Console Application” to create a new console project.
-
2
Add the following line of code in the declaration area of the project located at the very top of your code module:
using System.Data.Odbc;
-
-
3
Define the driver and the path of the Access database you want to use by adding following code:
string strCon = @"Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Northwind.mdb";
-
4
Create the SQL query statement to retrieve all the data in the Customers table in the database:
string SQLstr = "SELECT * FROM Customers";
-
5
Copy and paste the following code to create your ODBC object variables and execute the SQL statement defined in step four:
OdbcConnection ODBCconn = new OdbcConnection(strCon);
OdbcCommand ODBcmd = new OdbcCommand(SQLstr);
ODBcmd.Connection = ODBCconn;
ODBCconn.Open();
OdbcDataReader ODBCrdr = ODBcmd.ExecuteReader(); -
6
Loop through the results by adding a “while” loop. Display the “ID” and “Company” fields through the Console window:
while (ODBCrdr.Read())
{
Console.Write("ID:" + ODBCrdr.GetInt32(0).ToString());
Console.Write(" ,");
Console.WriteLine("Company:" + ODBCrdr.GetString(1).ToString());
}Console.ReadLine();
ODBCrdr.Close();
ODBCconn.Close(); -
7
Press “F5” to run the program and view the results.
-
1
References
- Photo Credit Stockbyte/Stockbyte/Getty Images