Connect to an Access Database

If your building a dynamic website and wish to collect information from visitors, for example a Guestbook, you'll need to store the data. One of most common ways to store data is in a database, for example a MS Access database.

There are two ways to connect to an Access database, one is DSN connection and the other is DSN-Less connection.

You maybe wondering which one you should use? Well, DSN-Less is alot faster than just DSN, But if you only have your running a small site it wont affect you much anyway.

Having said that, We do recommend you yes DSN-Less thought. And if you run a large website and web host supports it, We also recommend you use a MSSQL Server Database. If wish to use a MSSQL Database we have a tutorial on how to connect to MSSQL Database.

Below are examples of how to connect to an Access Database using the DSN and DSN-less methods.

DSN Connection:

<%
  Dim adoCon
  Dim strDSN

  strDSN = "dsnname"

  Set adoCon = Server.CreateObject("ADODB.Connection")
  adoCon.ConnectionString = "DSN=" & strDSN
  adoCon.Open
%>

DSN-Less Connection:

<%
  Dim adoCon
  Dim strDatabase
 
  strDatabase	= Server.MapPath("database.mdb")

  Set adoCon = Server.CreateObject("ADODB.Connection")
  adoCon.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & strDatabase & ";"
  adoCon.Open
%>

Important:

It is important to remember to always close the connection to your database within your pages. But how do you close the connection to your database? Well, the example below shows you how to do just that.

<%
  adoCon.Close
%>

Once you have finished with a database remember to add the code above to your page.

Written By: S2H, 14th October 2006

Bookmark

Advertisement