ASP C# Access Database connect code

What is this code?

This is a simple tutorial for connecting to an Access Database using C#. I have used it many times for uni assignments, and it has never let me down. It provides a quick easy way to connect without worrying about other complex and annoying stuff. All you need is a DB and an SQL query.

Lets go...

Place the .mdb file on your website somewhere accessable

You need to add the following at the top of each C# page you wish to use the DB on

using System.Data.OleDb;

Next, use this Code to connect to the DB and open a connection

string dbConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(@"./path/to/database.mdb");
OleDbConnection myConn = new OleDbConnection(dbConnect);
myConn.Open();

Now, to READ DATA from the Database

string strSQL = "SELECT * FROM tblUser"; //This is a standard SQL query, with respect to our database
OleDbCommand myCmd = new OleDbCommand(strSQL, myConn);
OleDbDataReader reader = myCmd.ExecuteReader(); //This executes the Query
while (reader.Read()) {
    Label1.Text = reader["UserAlias"] + reader["Password"]; //See below for explination
}
reader.Close(); //Close the 'reader'

To call each value from the Reader, you can use the form:

reader["colName"]

Where colName is the Column Name, i.e. UserAlias, or Password. Refer to the .mdb file for correct naming of Columns

OR if you want to WRITE TO the database

string strSQL = "INSERT INTO tblUser SET ..."; //Standard INSERT, UPDATE, REPLACE etc SQL query goes here
OleDbCommand myCmd = new OleDbCommand(strSQL, myConn);
myCmd.ExecuteNonQuery(); //This executes the query

Once you've finished performing your queries, don't forget to close the Database connection like a good programmer.

myConn.Close();

Thats it! The above code works fine for me, so it should work for you... If you get into trouble, let me know!

All the code provided here is avaliable for you to do whatever you like with, so feel free to implement these as part of your own scripts, just don't take my code as-is and change my name to yours.