Subscribe

RSS Feed (xml)

Connecting to a Microsoft Access Database

To connect to a Microsoft Access database, you must include the


System.Data.OleDb


namespace because all the ASP.NET classes that are required to connect to datasources


through an OleDB connection are located in this namespace.The ASPX page looks as


follows:


<html>


<head>


<title>Connecting to a Microsoft Access Database<title>


</head>


<body>


<form runat="server">


<h3>Connecting to a Microsoft Access Database</h3>


<p>


<asp:DataGrid id="dg1" runat="server"></asp:DataGrid>


</p>


<p>


<asp:Literal id="ltlError" runat="server"></asp:Literal>


</p>


</form>



</body>




</html>


Add the following code within the <script> tags:


Public Sub Page_Load(Source As Object, E As EventArgs)


Dim ConnectionString As String


ConnectionString =


"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" & _


Server.MapPath("Northwind.mdb") & ";"


Dim QuerySQL As String


QuerySQL = "SELECT * FROM Shippers"


Dim objConn As New OleDbConnection(ConnectionString)


Dim objCmd As OleDbCommand


objCmd = New OleDbCommand


objCmd.CommandText = QuerySQL


objCmd.Connection = objConn


Try


objConn.Open()


dg1.DataSource = objCmd.ExecuteReader()


dg1.DataBind()


Catch Err As Exception


ltlError.Text = Err.ToString()


Finally


objConn.Close()


End Try


End Sub


Comments


First, you must create a connection string that includes the driver and the source path of


the source database. In this example, this has been assigned to the string type variable


named ConnectionString. Remember that if you are using Microsoft Access 97, the


connection string is going to be as follows:


"Provider=Microsoft.Jet.OleDb.3.75;Data Source=" & _


Server.MapPath("Northwind.mdb") & ";"



Whereas when using Microsoft Access 2000 and XP, the string is as demonstrated in the




code.You must create the Connection and Command objects as well.The Connection


object's constructor is provided with ConnectionString, which contains the connection


string.The Command object's instance is assigned the query and the connection that it


will use to access the datasource.


Having established the basic settings for the Connection and the Command objects,


you enclose the rest of the code within a Try/Catch/Finally block to capture any type


of errors that arise. Afterwards, within the Try/Catch block, you open the connection


and call the ExecuteReader method of the command object.This method executes the


specified query text and returns the results to the DataGrid control that has been


assigned to it.


When you view the page in the browser, you will see all the records from the database


table specified in the query.




Technorati :

No comments:

Archives

Variety in the Web World