PDA

View Full Version : Get data from a database using ASP


Kings
May 3 '02, 10:56 AM
Introduction
One of the most common things in ASP, is to get data from a database. In this tutorial I'm going to show you how to get data from a database, and display it in a table.

Let's make a connection first
First we need to make a connection to our database.
I'm going to make a DSN-Less connection, because many webhosts don't offer a DSN-connection.


<%@ Language=VBScript%>
<% Option Explicit %>
<!--#include file="adovbs.inc"-->
<% Response.Expires = 0 %>

<%
'Declaring our variables
Dim objConn, objRS, strQuery, strConnection

'Create ADO Object
Set objConn = Server.CreateObject("ADODB.Connection")

'Our connection string, with the path to our database
strConnection = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("yourdb.mdb")

'Open up connection
objConn.Open strConnection %>


Now create a recordset
We've opened up a connection to our database. Next thing we have to do is open up a recordset to select our data.


<%
'Create our recordset
Set objRS = Server.CreateObject("ADODB.Recordset")

'Set our cursor types
objRS.CursorLocation = adUseClient
objRS.CursorType = adOpenStatic
%>


Select our data
Now we've opened our connection, and the record set. We're ready to select the data from the database.


<%
'Build up the query to select the data
strQuery = "SELECT Row1, Row2 FROM Table1"
'Select our data
objRS.Open strQuery, objConn, , , adCmdText
%>


Display data
Now we have selected our data, and it's ready to be displayed. We want to display it in a nicely formated table.


<table border="0" width="80%">
<tr>
<td width="40%">
Row 1
</td>
<td width="40%">
Row 2
</td>
</tr>
<%
'Let's print out our data
'Do Until objRS.EOF = True
While NOT objRS.EOF
Response.Write("<tr>" & vbCrlf)
Response.Write("<td width="40%">" & objRS("Row1") & "</td>" & vbCrlf)
Response.Write("<td width="40%">" & objRS("Row2") & "</td>" & vbCrlf)
Response.Write("</tr>" & vbCrlf)

objRS.MoveNext
Loop %>
</table>


Well, that was it!

We first made a connection, then created a recordset, then selected our data, and finally printed it out in a nicely formatted table.

Kings
May 3 '02, 11:24 AM
Here is adovbs.inc for the cursor types

Because I can't attach .inc files, you need to rename the file from .txt to .inc

Edit: sorry, attachments lost in the database transfer because the old host didn't have SSH :( --filburt1

Edit: no problem, added attachment again --Kings