| |||||||||||||||||||||||
|
Due to the commonality of some pages (for example, the recipe area of this site) having a database that an ASP page reads from to create a page can save a lot of time. Below is a pretty common shell I use for database access. Of course, the SQL changes and there are formatting things in there to create tables, etc. For example, in the recipes, there can be 20 different ingredients and they're each written to the page as a list item (<li>) until an empty one is reached and then the list is closed. And then each step of the instructions are a list-item in an ordered list.
<%@ LANGUAGE="VBSCRIPT %>
<%
Dim dbConn ' connection handle
Dim rs ' result set handle
Dim sSQL ' SQL statement
' to handle the errors yourself rather than having
' the page just not display (also handy for debugging
On Error Resume Next
' create the connection object
Set dbConn= Server.CreateObject ("ADODB.Connection")
' create the recordset
Set rs= Server.CreateObject ("ADODB.RecordSet")
' open the connection to the database as it is named in ODBC
dbConn.Open "DSN=dbname;UID=;PWD=;"
' if we managed to open the database
If Err.Number = 0 Then
' build the SQL statement you need
sSQL = "SELECT field_1, field_2 FROM SOME_TABLE"
' create a recordset object by executing the SQL
Set rs = dbConn.Execute (sSQL)
' if the SQL worked
If Err.Number = 0 Then
' and if what's returned isn't an empty set
If Not rs.EOF Then
' as long as we're not at the end
Do While Not rs.EOF
' write out the field values
Response.Write ("Field 1: " & rs("field_1") & "<br>" & vbCRLF)
Response.Write ("Field 2: " & rs("field_2") & "<br>" & vbCRLF)
' write out a blank line
Response.Write ("<br>" & vbCRLF)
Loop
Else
' write out that the query was bogus and there's nothing here
Response.Write ("Sorry, no data returned for that query.<br>" & vbCRLF)
End If
Else
' something went wrong with the SQL statement
Response.Write "---- Error running the query. ----<br>" & vbCRLF
Response.Write "Error Number: " & Err.Number & "<br>" & vbCRLF
Response.Write "Error Description: " & Err.Description & "<br>" & vbCRLF
End If
Else
' something went wrong opening the database connection at all
Response.Write "---- Error opening the database. ----<br>" & vbCRLF
Response.Write "Error Number: " & Err.Number & "<br>" & vbCRLF
Response.Write "Error Description: " & Err.Description & "<br>" & vbCRLF
End If
rs.Close set rs=nothing dbConn.Close set dbConn=nothing
|
|
| |||||||||||||||||||||||||||||||||