• missing xbfish.com image

Tag Archives: connect c# ms access

connecting C# to MS Access

To connect C# to Microsoft Access Database, we need to make use of OLEDB class. Below is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Data.OleDb;
 
class Test
{
    static void Main(string[] args)
    {
        //create the database connection
            OleDbConnection Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\database.mdb");
 
            //create the command object and store the sql query
            OleDbCommand Command = new OleDbCommand("SELECT rank, name FROM EMPLOYEE WHERE Employee_ID = 99999", Connection);
 
            Connection.Open();
 
           //create the datareader object to connect to table
            OleDbDataReader Reader = Command.ExecuteReader();
    }
}

Lets say if we decided to display the query result into some textbox, we do the following:

1
2
3
4
5
6
7
8
9
10
           //Iterate through the database
           while(Reader.Read())
           {
                //Assuming the first column data is a string
                name.Text = Reader.GetString(0); 
                //Assuming the second column data is a integer
                age.Text = Reader.GetInt32(1); 
           }
           //Close the database connection
           Connection.Close();

Simple eh? :D Hope it helps!