Dynamically Retrieve Recordset Data without Knowing Table Field Names
By using the Count property of the Recordset Fields Collection we can dynamically retrieve a recordset's data. The code below is a generic script that will retrieve the field name and the values in each row. Just make sure you change the connection string 'sConnString' to the location of your database and modify the SQL statement to Select from your table name.
<%@ Language="VBScript" %>
<% Option Explicit %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Dynamically Retrieve Recordset Data</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
</head>
<body>
<%
Dim oConnection, oRecordset, sSQL
sConnString="PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Server.MapPath("myDatabase.mdb")
Set oConnection=Server.CreateObject("ADODB.Connection")
Set Recordset=Server.CreateObject("ADODB.Recordset")
oConnection.open(sConnString)
sSQL = "SELECT * FROM myTable"
oRecordset.open sSQL, oConnection
If Not oRecordset.EOF Then
Response.write "<table border=""1""><tr>"
For i = 0 To oRecordset.Fields.Count - 1
Response.write "<td><strong>" & oRecordset(i).Name & "</strong></td>"
Next
Response.write "</tr>"
Do While not oRecordset.eof
Response.write "<tr>"
For i = 0 To oRecordset.Fields.Count - 1
If (Not IsNull(oRecordset(i).Value)) then
Response.write "<td>" & oRecordset(i).Value & "</td>"
Else
Response.write "<td> </td>"
End If
Next
Response.write "</tr>"
oRecordset.movenext
Loop
Response.write "</table>"
Else
Response.write "<p>No Records</p>"
End If
%>
If you have any code snippets to share with full credit given then send an email to Codesnippets - You'll receive full credit and a link back to your site.
Site developed by Michael Wall - Web Design Belfast N.Ireland.
Copyright © 2000-2008. All rights reserved.
|