• missing xbfish.com image

connecting C# to MS Access

missing xbfish.com image
Posted on

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!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">