Beginning Active Server Pages

Getting DB Content

A more often task, however, is to retreive information from a database. This can be done using ADO recordsets and the Execute statement to run an SQL query.

First, using the form we created in the last section, add a few records to the database. In this section, you will find out how to display them! First, we execute an SQL statement, and assign a variable to its result:

Set rData = cConn.Execute ("My SQL Statement")

First, add the code below to a file called viewusers.asp. We've come across it all before.

<%
Dim cConn, rData
'Open the db connection
Set cConn = Server.CreateObject ("ADODB.Connection")
cConn.Open "test_db","",""
'Execute the SQL 
Set rData = cConn.Execute ("SELECT * FROM MyUsers")
%>

All the last statement does is return all the fields and rows from the table MyUsers into the recordset rData. rData is now a standard ADO Recordset.

We can use the rData.MoveNext command in a Do...Loop statement to loop through the data, and check the rData.EOF property to see if we have reached the end. All you need to do now is retreive the values for each field. This is done using rData("FieldName"). Using this information, we can now write some code to loop through the available records, and output some HTML:

<%
Dim cConn, rData
'Open the db connection
Set cConn = Server.CreateObject ("ADODB.Connection")
cConn.Open "test_db","",""
'Execute the SQL 
Set rData = cConn.Execute ("SELECT * FROM MyUsers")
%>

<p>Below is a list of the current members</p>
<table border="1">
 <tr>
  <td><b>ID</b></td>
  <td><b>Name</b></td>
  <td><b>Email</b></td>
 </tr>
<%
Do While rData.EOF = False
    'output ID
    Response.Write " <tr>" & vbNewLine & "  <td>" & rData("ID") & "</td>" & vbNewLine
    'output name
    Response.Write "  <td>" & rData("Name") & "</td>" & vbNewLine
    'output email
    Response.Write "  <td>" & rData("Email") & "</td>" & vbNewLine & " </tr>" & vbNewLine
    rData.MoveNext
Loop
%>

and that's it! It's really that simple... Now take a look in your browser to see the list of members who have signed up!

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Never trust a programmer in a suit.” - Anonymous