VBScript Database Tutorial
VBScript Database Tutorial
com
Database Tutorial
Probably the most popular use for ASP scripting is connections to databases. It's
incredibly useful and surprisingly easy to do.
The first thing you need is the database, of course. A variety of programs can be
used to create it, but probably the most popular is Microsoft Access. You can also
use FoxPro or create it directly in an SQL Server using whichever utilities are
supplied with the server (Enterprise Manager in the case of Microsoft SQL
Server), or native SQL commands.
The choice of final format for the database is important. Almost any Windows NT
web server can host an Access or FoxPro database, but this method is
problematic - because of the inability to make changes to the structure of the
database while it is live, and because of performance considerations. Don't be too
scared off though - if you're looking to learn ASP Database interfacing, or you're
developing a new site or low traffic site, there's absolutely nothing to stop you
starting with an Access or FoxPro database.
The best method from several points of view is to create your database using
Access or FoxPro, and then upscale it to SQL Server - you can then use Enterprise
Manager to make changes while the database is live.
Because of the heavy server load involved in Internet Information Server 4 and
SQL Server, it is almost essential that you select a web host that offers dedicated
SQL Servers - especially where you are sharing servers (most often the case) or
you have a high-traffic Site.
We'll attempt here to show you the basics of database usage with Active Server
Pages and VBScript. We don't claim that these are the best methods available,
but they will get you started down the path to developing real Web Applications.
We will be developing a range of articles over coming weeks that will show you
how to optimise your code to cause the minimum possible server load and
provide the maximum possible performance for your application.
Page 1 of 10
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Database Tutorial
1. System DSN
A datasource created on the web server by the administrator of the server. The
most popular type of DSN and generally a lot more reliable.
2. File DSN
Essentially a connection that your script makes itself each time access to the
database is required, specifying the path to and name of the database. The
database must reside on the server in a directory that your script can access for
this to work.
The code below is designed around a System DSN - we will incorporate File DSN
code over coming weeks.
<%
Session.timeout = 15
Set conn = Server.CreateObject("ADODB.Connection")
conn.open "ODBCDSNName","username","password"
Set Session("MyDB_conn") = conn
%>
Should be done at the end of each page for each Datasource opened.
<%
conn.close
set conn = Nothing
%>
Page 2 of 10
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Database Tutorial
To create a recordset containing all of the records in one table of the database,
without sorting them:
<%
strSQLQuery = "SELECT * FROM tablename "
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQLQuery, conn, 3, 3
%>
To create a recordset containing only those records in one table where the field
'Name' consists of only the word 'Fred':
<%
strSQLQuery = "SELECT * FROM tablename WHERE Name = 'Fred'"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQLQuery, conn, 3, 3
%>
To create a recordset containing all of the records in one table and sort them
alphabetically based on the field Name starting at 'a':
<%
strSQLQuery = "SELECT * FROM tablename ORDER BY Name ASC"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQLQuery, conn, 3, 3
%>
To create a recordset containing all of the records in one table and sort them
alphabetically based on the field 'Name' starting at 'z':
<%
strSQLQuery = "SELECT * FROM tablename ORDER BY Name DESC"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQLQuery, conn, 3, 3
%>
If you want to be able to be sure of selecting only one particular record from a
database, each table should have a 'Unique Key' field - usually a simple auto-
incrementing number field. You can then select, update or delete records in the
database using this field as the criteria.
<%
strSQLQuery = "SELECT * FROM tablename WHERE RecordID = 15"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQLQuery, conn, 3, 3
%>
Page 3 of 10
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Database Tutorial
<%
strValue = rs("FieldName ")
%>
strValue can of course be any variable name, FieldName is the field name in the
table that makes up the recordset. Multiple recordsets can be opened for the
same database and/or table - just change the 'rs' to whatever name you want to
give to each recordset. Standard SQL queries can be used to update, add or
delete records, or create recordsets based on conditions. For example:
<%
strSQLQuery = "DELETE * FROM tablename WHERE Name = 'Fred'"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQLQuery, conn, 3, 3
%>
<%
strSQLQuery = "DELETE * FROM tablename WHERE Name = 'Fred' AND Address
= 'Smith St'"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQLQuery, conn, 3, 3
%>
<%
strSQLQuery = "DELETE * FROM tablename WHERE Name = 'Fred' OR Name =
'John'"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQLQuery, conn, 3, 3
%>
<%
strSQLQuery = "UPDATE tablename SET FieldName1 = " & strValue1 & " WHERE
FieldName2 = " & strValue2 & ";"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQLQuery, conn, 3, 3
%>
<%
strSQLQuery = "INSERT INTO tablename (FieldName1, FieldName2) VALUES (" &
strValue1 & ", " & strValue2 & ")"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQLQuery, conn, 3, 3
%>
There are some minor differences in the SQL queries used for Access versus SQL
Server - the above works on SQL Server.
Note:
tablename would normally be just the name of the table in the database when
using an Access database for instance, but when using SQL Server you also need
to specify a UserName with access permissions to that database - in the format
'UserName.TableName'. Talk to your server administrator for more information.
Page 4 of 10
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Database Tutorial
1. The Statement
Essentially determines the purpose of the SQL query - to retrieve records, delete
them, change them, etc.
2. The Clause(s)
Determines which records are affected by the query and how they are sorted -
and can also perform a number of other functions, including grouping of
indentical records.
3. The Operation(s)
Actually perform operations on the records, such as combining or joining result
sets.
SQL SubQueries
Statements
SELECT Statement Retrieve records from a database.
INSERT INTO
Insert records into a database.
Statement
SELECT...INTO Select records from one table/database and insert them
Statement into another table/database.
UPDATE Statement Update/change records.
Clauses
FROM Determines the tables in the database that the query is to
Clause affect/retrieve.
WHERE
Determines the selection criteria to be used.
Clause
Determines the field(s) to be used to sort the results of a SELECT
ORDER BY
or SELECT...INTO statement, together with the order - either
Clause
'ASC' (ascending) or 'DESC' (descending).
GROUP BY Determines the field(s) to be used for the grouping of the results
Clause of a SELECT or SELECT...INTO statement.
HAVING Specifies which grouped records are displayed in a SELECT
Clause statement with a GROUP BY clause.
Page 5 of 10
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Database Tutorial
Operations
Used in combination with both Statements and Clauses for
UNION
combining the results of two or more independent queries or
Operation
tables.
INNER JOIN
Operation
LEFT JOIN
Operation
RIGHT JOIN
Operation
Part Description
comparison An expression and a comparison operator that compares the
expression with the results of the subquery.
expression An expression for which the result set of the subquery is searched.
sqlstatement A SELECT statement, following the same format and rules as any
other SELECT statement. It must be enclosed in parentheses.
You can use a subquery instead of an expression in the field list of a SELECT
statement or in a WHERE or HAVING clause. In a subquery, you use a SELECT
statement to provide a set of one or more specific values to evaluate in the
WHERE or HAVING clause expression.
Use the ANY or SOME predicate, which are synonymous, to retrieve records in the
main query that satisfy the comparison with any records retrieved in the
subquery. The following example returns all products whose unit price is greater
than that of any product sold at a discount of 25 percent or more:
Page 6 of 10
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Database Tutorial
Use the ALL predicate to retrieve only those records in the main query that satisfy
the comparison with all records retrieved in the subquery. If you changed ANY to
ALL in the above example, the query would return only those products whose unit
price is greater than that of all products sold at a discount of 25 percent or more.
This is much more restrictive.
Use the IN predicate to retrieve only those records in the main query for which
some record in the subquery contains an equal value. The following example
returns all products sold at a discount of 25 percent or more:
Conversely, you can use NOT IN to retrieve only those records in the main query
for which no record in the subquery contains an equal value.
Use the EXISTS predicate (with the optional NOT reserved word) in true/false
comparisons to determine whether the subquery returns any records.
You can also use table name aliases in a subquery to refer to tables listed in a
FROM clause outside the subquery. The following example returns the names of
employees whose salaries are equal to or greater than the average salary of all
employees with the same job title. The Employees table is given the alias “T1":
SELECT LastName,
FirstName, Title, Salary
FROM Employees AS T1
WHERE Salary >=
(SELECT Avg(Salary)
FROM Employees
WHERE T1.Title = Employees.Title) Order by Title;
The AS reserved word is optional.
Examples
Page 7 of 10
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Database Tutorial
Lists the name and unit price of every product whose unit price is the same as
that of Aniseed Syrup.
<%
' Move to the first record
rs.movefirst
<%
rs.delete
%>
To loop through a recordset, writing a field from each record to the web page:
Page 8 of 10
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Database Tutorial
<%
' Open the recordset first (see above)
do until rs.eof
response.write(rs("FieldName") & "<br>")
rs.movenext
loop
%>
The same thing, but starting with the last record and working in reverse:
<%
' Open the recordset first (see above)
rs.movelast
do until rs.bof
response.write(rs("FieldName") & "<br>")
rs.moveprevious
loop
%>
The most important thing to remember is that there are essentially four steps
involved:
2. Specify a set of records (Recordset) that you want to retrieve, delete, update
etc.
3. Do whatever you need to do with those records - ie. write them to the web
page.
Once you get a handle on the basics here, the next step is to work out how SQL
Queries work - check our Database Section for the SQL Query reference.
Page 9 of 10
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Database Tutorial
<%
Set rs = Server.CreateObject("ADODB.Recordset")
strSQLQuery = "SELECT Count(*) AS MyRecordCount FROM tablename "
rs.Open strSQLQuery, conn, 3, 3
response.write(rs("MyRecordCount") & "<br>" & vbCrLf)
%>
Counting records in this way is desirable where you don't need to use the
contents of the set of records you need to count - it imposes much less load on
the server. A full range of SQL Queries can be used to count records matching
specific criteria.
Single quotes - ' - in SQL Query strings will break the query and generally
cause an 'Incorrect Syntax Near' error, but one simple line of code can be used
to strip out any single quotes:
<%
strSQLQuery = Replace(strSQLQuery, "'", "", 1, -1, 1)
%>
In situations where you want to add the single quotes to the database record,
you can replace them with double quotes:
<%
strSQLQuery = Replace(strSQLQuery, "'", "''", 1, -1, 1)
%>
Page 10 of 10