Professional Documents
Culture Documents
(If you appreciate these notes, please visit Syslist.com, a site developed by the author.
Thank you!)
1. Basics
2. Variables, Math
3. Control Stuctures
4. Built-in VB functions
5. Objects
6. The Response Object
7. Forms
8. Collecting Form Info
9. The Request Object (& Cookies)
10. The Session and Application Objects (*QueryString Shortcut)
11. Common ASP Components
12. Reading and Writing Files on the Web Server (*Code Insertion)
13. Debugging ASP Scripts and Handling Errors
14. Using Databases
15. Reading from a Database Using ASP
16. Inserting, Updating, and Deleting Database Records (with the Recordset
Object)
17. The Recordset Object
18. Using SQL Statements to Query Data
19. Advanced Database Techniques
20. External Notes
*These notes are based on information taken from random sources on the Internet, the author's
personal knowledge, and SAMS Teach Yourself ASP 3.0 in 21 Days (good book). - 4/12/2000
Day 2 - Basics
Back to Top
Back to Top
• Conditional logic controls (If condition Then codeblock End If): you can
use an if/then/end if statment, an if/then/else/end if statment (which
can be nested; eg, if/then/else-if/then/else or if/then-if/then/else; the
latter allows for "if x is true, then check y [the next if], else z), an
if/then/elseif statement (just requires one "end if" at the end, as opposed to
one for every nested "if" statement. A mere time saver). Remember to always
finish code with End If where appropriate;
• For nested conditions more than three levels deep, use:
Select Case expression
Case value1
code_block for when expression equals value1
Case value2, valueN
code_block for when expression equals value2 or valueN
Case Else
code_block for when expression matches no named value. *note: this
is good for preventing errors*
End Select
• Looping logic controls: (Do While...Loop) executes a block of code while
certain conditions are true. Do Until...Loop executes until a certain condition
is met.
Do While condition
code_block
Loop
• You can also make sure the code_block is run at least once by putting the
"while condition" below it:
Do
code_block
Loop While condition
• HTML tags that fall within ASP control structures are affected by them, as well;
• Use the (Exit Do) statement to end a loop abruptly. This is often paired with an
If...Then;
• (While...Wend) is similar to (Do While...Loop) - better not to use it;
• (For...Next) is used when the number of times the code should loop is known.
counter is a numeric variable that keeps track of the loop. counter begins at
startvalue. It increases, each loop, by stepvalue. If you omit Step
stepvalue, ASP will assume a value of one.
For counter = startvalue to stopvalue Step stepvalue
code_block
Next
• (For Each...Next) is used to iterate through each element in a group:
For Each item in group
code_block (item)
Next
• Nesting loops results in each nested loop completing a cycle for every individual
count of the parent loop (eg, multiplication table example);
• Branching logic controls: two kinds: subroutines (for performing actions) and
functions (for computing values). Subroutines do *not* return a value. Branching
logic is used for code that is repeated often or may need to be changed frequently.
Feel free to include any other kind of logic within a branching logic control.
• Subroutine (only called by itself):
Sub routinename (arg) *Note: arg is not required*
code_block
End Sub
• Variables declared in the main part of your script are global - they can be
accessed by any logic control. Variables declared inside a subroutine are local to
it.
• Function (can be put into an expression, etc):
Function functionname (arg)
code_block
End Function
Back to Top
• Formatting functions:
o FormatDateTime(expression, optional_argument) - this is used to
format date/time data. Optional_argument can be one of five things:
vbGeneralDate - displays date as short date and time as long time.
This is the function's default setting. It's value is 0;
vbLongDate - displays date using long date format, value is 1;
vbShortDate - displays date using short date format, value is 2;
vbLongTime - etc, value is 3;
vbShortTime - etc, value is 4;
o FormatCurrency(value, arg1, arg2, arg3, arg4) - this is used to
format currency values. Arg1 is the number of digits after the decimal
place (-1 for default). For arg2-4, a value of -2 = default, -1 = on, -2 =
off. Arg2 specifies whether to add the leading zero to values that are less
than one, arg3 specifies whether to enclose negative values in parenthesis,
and arg4 specifies whether to use the delimiter to group digits (in the
U.S., the delimiter is a comma;
o FormatNumber(value, arg1, arg2, arg3, arg4) - works just like
FormatCurrency, minus the dollar sign;
o FormatPercent(value, arg1, arg2, arg3, arg4) - works just like
FormatCurrency, but returns a percentage;
• Math functions (see pages 130-131 for them all). Note: Abs(number) returns
absolute value, Int(number) returns first integer less than or equal to number,
Fix(number) returns first integer greater than or equal to number,
Round(number) rounds to nearest integer; Round(number, dec) rounds to dec
places after the decimal point;
• Placing Randomize at the top of a page allows you to call Rnd, which will contain
a random number less than one and greater than zero. To change those bounds,
call: (upperbound - lowerbound) * Rnd + lowerbound;
• Date functions (note: #9/18/99# refers to November 18, 1999. Whenever inputting
a date, you must put it in between pound signs. "9/18" refers to November 18th of
the current year, whatever that is):
o Date returns the current date. It can be stored in variables or
utilized/output as is;
o Time returns the current time. It can be stored in variables or
utilized/output as is;
o Now returns the current date and time;
o DateAdd(interval, number, date) adds the number of intervals to
the date specified. Interval must be put in quotes because it is a string.
Interval can equal: yyyy (for year), q (for quarter), m (for month), d (for
day), ww (for week of year), h (for hour), n (for minute), s (for second).
DateAdd will not return an invalid date - it'll just try its best with what you
give it. Make number something negative (perhaps 1 - Weekday(date))
to go back in time instead of forwards;
o DateDiff(interval, date1, date2, first_dow, first_woy)
returns the number of intervals between date1 and date 2. When
operating, DateDiff counts the second date, but not the first. Intervals are
same as for DateAdd. If date2 comes after date1, the return value is
positive. First_dow and first_woy are optional - they let you specify
what day is the first day of the week, and what week is the first week of
the year:
vbSunday (value = 1; default);
vbMonday (value = 2);
vbTuesday (value = 3);
vbWednesday (value = 4);
vbThursday (value = 5);
vbFriday (value = 6);
vbSaturday (value = 7);
---------------
vbFirstJan1 (value = 1; default);
vbFirstFourDays (value = 2);
vbFirstFullWeek (value = 3);
o DateSerial(year, month, day) creates a date value that you can then
stick into a variable. Use this if year, month, or day are variables
themselves, since you can't simply write #month/day/year#.
DateSerial(99, 5, 1 - 3) returns 4/28/99; in other words, three days
before 5/1/99;
o TimeSerial(hour, minute, second) ...etc;
o Timer returns the number of seconds elapsed since midnight;
o DatePart(d_part, date, first_dow, first_woy) retrieves a portion
of a date. First_dow and first_woy are optional (they let you specify
what day is the first day of the week, and what week is the first week of
the year), and d_part is a string (as in interval, DateAdd). Values are
returned as a number.
o Year(date) returns the year portion from date (a number);
o Month(date) returns the month portion from date (a number);
o MonthName(monthNumber, abbrev) returns a string with the name of the
month. MonthNumber ranges from 1 to 12. Abbrev is optional - if set to
true, it will abbreviate the returned string (eg, "Nov");
o Day(date) ...etc;
o Weekday(date) ...etc;
o Hour(time) returns the hour portion from time;
o Minute(time) ...etc;
o Second(time) ...etc;
• String Functions (the first few are great for de-sensitizing user input. Feel free to
combine them!):
o UCase(string) returns string with all its letters converted to uppercase;
o LCase(string) returns string with all its letters converted to lowercase;
o LTrim(string) removes all spaces from left side of string;
o RTrim(string) removes all spaces from right side of string;
o Trim(string) removes all spaces from both sides of string;
o Space(number) returns a string consisiting of number spaces (not really
useful, except for within <pre> tags);
o String(number, char) returns a string consisting of char repeated
number times;
o Len(string) counts the number of characters in string;
o StrReverse(string) returns string with the characters in reverse
order;
o StrComp(string1, string2, comparetype) is used to perform string
comparisons. Omit comparetype to take into account letter case,
otherwise use 1 to ignore case. StrCompare returns -1 if string1 is less
than string2, 1 if the reverse, and 0 if they are the same;
o Right(string, number) returns the number rightmost characters of
string;
o Left(string, number) ...etc;
o Mid(string, start, length) returns length characters from string,
starting at position start (length and start should be numbers);
o InStr(start, string1, string2, comparetype) checks if and where
string2 occurs within string1. Start is optional; it determines where in
string1 to start looking. Comparetype is optional. InStr returns 0 if the
check fails, and returns the starting position of string2 within string1 if
it succeeds.
o InStrRev(string1, string2, start, comparetype) works in
reverse (ie, checks from right to left). Start is -1 by default. Character
positions (in return values) are still numbered from left to right, though;
o Replace(string, find, replace, start, count, comparetype) is
used to replace occurences of find with replace in string. Count is -1
by default (replace every occurence). Remember to put commas in place
of start, count, or comparetype if you want to use one, but not the
other;
o Filter(arrStrings, SearchFor, include, comparetype) searches
the array, arrStrings, for SearchFor, and returns a subset of the array.
Include can be true or false - true returns strings that match, false returns
strings that don't match;
o Split(expression, delimiter, count, comparetype) splits a string
into an array of strings. Delimiter indicates what is used to separate the
intented sub-strings in expression (its default is the space), and can be
more than one character. Count limits the number of sub-strings that will
be created (default is -1, for no limit);
o Join(stringarray, delimiter) takes an array of strings and joins
them into one string, using delimiter to separate them (default is, again,
the space);
o LBound(array) returns the smallest valid index for array. This is
normally 0;
o UBound(array) returns the largest valid index for array. This is the
index of the last element in the array;
o Use the above to iterate through an array of unknown size: For iIndex
= LBound(myarray) to UBound(myarray)...;
o Asc(string) returns the ANSI code for the first character of string;
o Chr(integer) returns the opposite of Asc. Use Chr to access and print
characters that otherwise aren't on the keyboard, like the copyright
symbol: Chr(169);
Back to Top
Day 6 - Objects
• Functions make your code more simple and readable; Objects take that to the next
level. Objects are composed of properties (things that describe them), methods
(things that can be done with them), and events (something generated by the
object that causes special action to be taken). Objects have "instances" - for
example, object "car" has instances "Explorer," "Jeep," etc. Each of those has a
unique set of properties defined by "car";
• To access object properties: ObjectVariableName.Property;
• Methods receive arguments, and often affect the value of properties (eg, the
accelerate method increases the speed property). To access methods:
ObjectVariableName.Method;
• The six built-in ASP objects:
o Response - used to send output. Response also controls how and when
data is sent, and do stuff with cookies;
o Request - used to retrieve data from the client. QueryString data (seen at
the end of URLs) is an example of a request object;
o Application - used to share information among several clients visiting
the same group of pages. Application refers to all the .asp pages in a
directory and its subdirectories. One instance of this object is created and
shared among all clients;
o Session - refers to a single client accessing an application. A new
instance is created for each session, and carries information between pages
for client;
o Server - has a few basic properties and methods: the CreateObject
method is used to create an instance of a server component (a server
component is a package of related objects). To use: Set ObjInstance =
Server.CreateObject("Class.Component"). The ScriptTimeout
property can be used to specify the length of time a script may be allowed
to execute before an error occurs. To use: Server.ScriptTimeout =
seconds. The HTMLEncode method replaces reserved HTML characters in
a string with their ASCII equivalent. To use:
Server.HTMLEncode(string). URLEncode does the same for URLs. The
MapPath method coverts a virtual path into a physical path. To use:
Server.MapPath(virtual_path);
o ObjectContext - used to link ASP and the Microsoft Transaction Server
(MTS).
o ASPError - allows you to obtain information about script errors in your
pages.
• A "collection" is a set of name/value pairs. "?name=John&sex=Male" contains
two name/value pairs, which are stored in the QueryString (a collection in the
Request object). If you have an object instance named Texas that contains a
collection named Cities, and Cities contains a pair named "Capital", you can
find the corresponding value using the Item method -
Texas.Cities.Item("Capital"). Item is the default method for collections, so
you can omit it. You can also access values in a collection by using an index
number, as in arrays. Collection indexes, however, start at 1 (as opposed to zero).
Use: Object.CollectionName.Count when counting through a collection with
an unknown number of pairs.
• ASP components - objects created by a third party that you can download and use
to make programming easier;
• Use the Class statement to create a simple object:
Class classname
public propertyname
private propertyname
public Sub methodname(args)... End Sub
private Function methodname(args)... End Function
etc...
End Class
• Creating an instance of an object is called "instantiation". To do so, use: Set
variablename = objectexpression. Objectexpression is either the name of
an object, another instance of the same object type, or the keyword New followed
by a class name. (eg, Set MyCar = New Car).
• Set the Color property of instance MyCar (object Car) like this: MyCar.Color
= "blue";
• A better way to change the value of a property is to do so through a method
included in the object (eg, the Sub and Function methodname(args)...);
• Use: Set objectinstance = Nothing to free up system memory, once an
instance no longer needs values;
• When an event is generated, special code called an event handler can be executed.
Two common events are Initialize (generated when an instance of an object is
created) and Terminate (...when destroyed). Creating a method in a class
statement called Class_Initialize will result in that method's code block
automatically activating when an instance of that object is created.
Back to Top
Back to Top
Day 8 - Forms
• <form> - defines a form. Its action attribute gives the URL of the application
that will receive the data (put URL in quotes). Form-processing aps ususally go in
a directory named cgi-bin;
• The optional enctype attribute should be included with a value of "text/plain" if
the action attribute will contain a mailto, and with "multipart/form-data" if the
form will be used for file uploading. In both cases, the method attribute must be
set to post;
• The method attribute determines how form data will be sent to the server. If set to
GET, it will be sent through the querystring. If set to POST, it will be sent in a
separate transmission. Small forms with a few short fields should be sent via the
GET method. If security is an issue, select POST;
• Server-side applications can be accessed through querystrings appended to
hyperlinks (in GET-style fashion). When doing this, however, make sure to
replace the "&" that separates name/value pairs in the querystring with a
"&", otherwise the browser will get confused;
• If using a mailto as the action attribute, use javascript to inform a user that their
form has been processed (they won't know otherwise);
• The input tag is used to define most of a form's possible controls. It has two
required attributes: type and name. The type attribute can include:
o text - defines a text entry field. The size attribute determines the width of
the display field (in chars), the maxlength attribute determines how many
total characters to accept from the user, and the value attribute puts a pre-
selected value into the field;
o password - simply a text field that masks user input as it is being typed;
o file - opens a dialog box that allows users to select a file. Use the accept
attribute to constrain the types of files that the user can select - its value is
a comma-separated list of MIME encodings. Remember to change the
enctype attribute to "multipart/form-data";
o checkbox - requires the value attribute. The optional checked attribute
(no value) will start a box off as checked. After closing the input tag, you
should write what you want the user to see as the value of the checkbox;
o radio - requires the value attribute. Every radio button in a group should
have the same name. One member in a group may contain the optional
checked attribute;
o submit - has no required attributes; it will simply submit a form's values
to the URL specified by action. Specifying a value attribute will change
the submit button's label, specifying a name and value attribute will (in
addition), send the extra name/value pair along with the rest of the form's
name/value pairs;
o reset - has no required attributes. You can change the button's label with
the value attribute;
o hidden - requires the value attribute. This is simply a way to hide a
name/value pair in a form. If you want to get information from one form
into another (without making a user re-type it), this is a good way;
• The textarea tag creates a mutiline text entry area. Body content will flow above
and below but not around a textarea box. Control height (in rows) and width (in
characters) with the rows and cols attributes. To make text in a textarea wrap,
include the wrap attribute. Setting wrap to virtual will cause the text to be
transmitted to the server exactly as it was typed (with line breaks only where the
user pressed "enter"). Setting it to physical causes text to be transmitted the way
it looks to the user;
• The select tag, with its option-tagged items, creates a pull-down or scrolling
menu. The multiple attribute lets a user choose more than one item in the menu.
The size attribute determines how many items in the menu are visible at once -
anything more than one will result in a scrolling menu. The select tag gets the
name attribute, the option tags get the value attributes;
Back to Top
• When a form has its method set to POST, you use the
Request.Form(variablename) collection to retrieve its values. When set to
GET, you use the Request.Querystring(variablename) collection.
Variablename should be equal to the name property of the relevant form field.
You can also simply use Request(variablename) - this only fails if a name is
used in both a page's querystring and a form;
• Response.Redirect can be used in conjunction with list boxes (menus) as a
navigational tool. The value of each option should be set to a URL, and the
action value of the form should be set to an ASP file called "redirect.asp", or
something;
• If you group checkboxes with one name (different values), and a user selects more
than one checkbox, the named group is returned as a comma-delimited list. You
can:
o Use the split function to turn that list into an array. After that, you can
use loops to determine what has or has not been checked (pg 277), or
whatever. Note that comma-delimited lists are spaced, so splitting one will
leave a leading space on each item in the array (except for the first). You
will have to trim it off;
o Give each checkbox a different name (same value), and then use multiple
"If" statements to parse through the results;
• If you will be collecting an unknown number of form results (for example, from
X select boxes...), you can use: For Each varname In Request.Form to rotate
through the results. varname represents the name aspect of a pair;
Request.Form(varname) represents the value aspect of a pair.
• As opposed to using forms, you can make use of hyperlinks with a querystring
attached to the end;
Back to Top
Back to Top
• If state *must* be maintained for all visitors, and: A) security is not an issue, B)
there is little data to pass, then use the querystring. Pass information from page to
page by adding the appropriate query string to the end of each and every link
following the page that requests the needed variables. <a href =
"somepage.asp?<%=Request.QueryString%>"></a>
• The Session object is used to maintain state on a person-by-person basis, for the
duration of a user's visit to the website. It can store arrays and objects; however,
all Session variables for each user are stored in the web server's memory, so this
should not be used in sites with many concurrent users. Create session variables
as follows: Session(variableName) = value;
• A numeric ID, the SessionID, is stored (as a cookie) on the user's machine (it can
be found in the Cookie header). Call it with Session.SessionID. Note that if the
webserver restarts, duplicate SessionID's may be created;
• Set the end of a session with: Session.Timeout = time_in_minutes. This value
should probably never be higher than 20 minutes, or so. Destroy a session
instantly with Session.Abandon;
• To put an object in the Session, use: Set Session(variableName) =
Server.CreateObject(ObjectName);
• The Session object contains two collections: Contents, which contains all non-
object variables, and StaticObjects;
• The Count property can be used on the Session object (eg,
Session.Contents.Count returns the number of variables in Contents);
• An ISAPI (Internet Server Application Programming Interface) filter called
Cookie Munger will simulate cookies, so that you may use the Session object
with users that disable them. However, it is very intense for the web server, and
should only be used on low volume sites;
• The Application object is used to store global variables - accessible from any ASP
page, by any user. Create application variables as follows:
Application(variableName) = value;
• To prevent more than one user from changing an application variable at once,
use: Application.Lock and Application.Unlock before and after the change
statement;
• Use: Sub Application_OnStart... End Sub, and Sub Session_OnStart... End Sub to
create all the session and application variables that will exists from the moment
the web server is up and running, and to set initial values for those variables.
These OnStart events must appear in the Global.asa file that is placed in the
website's root directory. Use the similar OnEnd event for cleanup type
maintenance;
Back to Top
• Browser Capabilities (BrowserType) is a component that does just what the name
says. To keep its abilities up to date, download newer versions of "browscap.ini"
(the companion file to browscap.dll) from http://www.asptracker.com/;
o Properties you can check for w/Browscap: browser, version, platform,
cookies, backgroundsounds, vbscript, javascript, tables, frames,
activexcontrols...;
o Use BrowserType as follows: If ObjBC.Browser = "Netscape"
Then...;
Back to Top
Day 13 - Reading and Writing Files on the Web Server (+ Code Insertion)
• Server-side includes allow you to write commonly used code and stick it into any
page in a site. They are always executed *before* any ASP code is executed. To
insert a page into another page this way, use: <!--#include
virtual="fullpath/something.asp"--> ;
• Server.Transfer and Server.Execute are new methods to IIS 5.0 that also
enable code insertion;
o Server.Execute(path) executes the ASP script specified, and can be
placed anywhere in a page. It's better than server-side includes because it
can be used conditionally, it is worse because it can't make use of
procedures or page-scope variables in the calling page;
o Server.Transfer(path) transfers control to another ASP page without
requiring another network trip between client and server. In addition, it
allows you to access any Form and Querystring values available to the
calling page. However, if you want a new object context (ie, so you can
pass a new value through the querystring), don't use this - use
Response.Redirect. In addition, Server.Transfer may break the
relative links on the page you transfer to, so beware;
• To open a file (instantiate the text stream object) so that you may read it, or write
to it:
o Use the OpenTextFile method of the file system object: Set
objOpenFile = objFSO.OpenTextFile(filename, mode, create,
format). mode has three possible values - ForReading (1), ForWriting (2),
or ForAppending (8). If filename is not found, a value of True (in the
create spot) will create it (the default is false). format indicates whether
to open the file as ASCII or Unicode (-2 for default, 0 for ASCII, -1 for
Unicode);
o Use the OpenAsTextStream method (if the file you want has already been
instantiated): Set objOpenFile = objFile.OpenAsTextStream(mode,
format);
o Use the CreateTextFile method (if you want to create or overwrite a file):
Set objNewFile = objFSO.CreateTextFile(filename, overwrite,
format);
o Before destroying an instance of the text stream object, you must close it:
objOpenFile.Close;
Back to Top
Back to Top
• The columns of a database table ("the object") describe the properties of the
object, whereas each row is a unique instance of the object. Rows in a database
table are records, and columns are referred to as fields. A record is a single
instance of the object, as a field is a single property of the object;
• If a property of an object is an object in itself (eg, has its own properties), then it
should get its own table, and be referenced in the parent table. Merging the two
related tables creates a flat-file database, which is not as efficient as separate
tables (a relational database). A relational database represents each object,
related or not, as its own database. A normalized database is streamlined to not
contain any repetitive data;
• Any ODBC-compliant database an be accessed through ASP. Such a database
adheres to the Open DataBase Connectivity standard outlined by Microsoft;
• A database is the most effective and efficient method of storing information.
However, connecting to a database through ASP is expensive; small bits of data
are best read from a text file or cookie, which are much easier to read. When the
information being stored needs to be long lasting and is not user-specific, text
files are a good way to go. For example, a list of bad credit card numbers would
best be kept in a text file;
• A vast number of existing applications already use databases to store information.
You can probably access these databases through ASP;
• To create a database through Access 2000:
o Run Access. A dialog box will appear. Choose to create a Blank Access
Database. Name the database file something.mdb. Choose Create Table in
Design View. Enter the columns for the table into the rows of the resulting
matrix (their name, data type, and description);
o Data types supported by Access: Text (255 alphanumeric chars or less),
Memo (65k chars or less), Number (numeric values), Date/Time, Currency
(supports up to four digits of decimal precision), Yes/No (for columns that
can have one of two values), Autonumber (automatically increments to
uniquely identify each row). Note that these data type names don't
perfectly match those of other database programs - you'll have to learn
theirs also;
o Save the table (and name it). Close the Design view, and select the table
you created from the inital set of options you were shown. Add some
information into the table, and you are all set!
• To communicate with a database through an ASP page, you need to use the
ActiveX Data Objects component (ADO). It contains two useful objects - the
Connection object and Recordset object
Back to Top
• The Connection object is used to hold information about the data store you want
to access. It is part of the ADOBD package. (Set objConn =
Server.CreateObject("ADODB.Connection")). If using multiple Access
databases, or mixing Access and other databases, you would use multiple
instances of the Connection object;
• A System DSN is a file that contains information about the database such as where
it is and what kind of database it is. DSN stands for Data Source Name. To create
a System DSN:
o Go to Administrative Tools and load Data Sources (ODBC). Click the
System DSN tab. Click Add. Choose Microsoft Access Driver (*.mdb)
and click Finish;
o Enter something.dsn for the Data Source Name. You will use this to
reference the DSN in ASP pages. Click Select, and choose the .mdb file
for the database. Click Ok, three times;
• Open the connection object with:
objConn.ConnectionString = "DSN=something.dsn"
objConn.Open strUsername, strPassword
-or-
objConn.Open "DSN=something.dsn", strUsername, strPassword
-username and password are used if the host requires it;
• You can replace "DSN=something.dsn" in a DSN-less connection with:
o "DRIVER={Microsoft Access Driver (*.mdb)};" &
"DBQ=PhysicalPath\something.mdb"
• The Recordset object is used to contain all the records in a table, or a subset of
those records: Set objRS = Server.CreateObject("ADODB.Recordest");
• Fill the recordset with records by using the Open method: objRS.Open
source, connection, cursortype, locktype, commandtype;
o source - either a command object or a string that relates to commandtype
("mytable");
o connection - either a Connection object or a string containing the
connection information;
o cursortype - indicates the way you want to move through the recordset.
Default is the ADO constant adOpenForwardOnly, which means you can
only move forward;
o locktype - affects whether you can write to the table, and if so, how.
Default is adLockReadOnly, which makes the table read-only;
o commandtype - indicates how the source parameter should be evaluated.
adCmdTable indicates that source is a table name;
• You can implicitely create a connection object by simply instantiating the
Recordset object, then opening it (with the connection parameter correctly set
to everything that would go into the Connection object's ConnectionString);
• ADO constants are not built into ASP - you must include the adovbs.inc file to
use them. Copy it from c:\Program Files\Common Files\System\ado\ and paste it
into your Web root directory. Then you can use: <!--#include
virtual="/adovbs.inc"-->;
• The METADATA tag may be used to import type-library constants into a page.
As an alternative to including adovbs.inc, you could use: <!--METADATA
TYPE="TypeLib" File="\msado15.dll"--> (you must put msado15 in your
root web, first). You can put this statement into your global.asa;
• Remember to always close (and set to Nothing) both objConn and objRS when
you are done with them!!!
• For more information on how to connect directly through OLEDB (circumventing
ODBC driver), read www.4guysfromrolla.com/webtech/063099-1.shtml;
Back to Top
Day 17 - Inserting, Updating, and Deleting Database Records (with the Recordset
object)
Back to Top
Back to Top
• With SQL, you can restrict the data returned by a database to only the information
you are interested in. Note: SQL is not case-sensitive by default;
• The syntax of an SQL query is as follows: objRS.Open SQLStatement,
ActiveConnection, CursorType, LockType. Before this, you must set:
SQLStatement = SELECT_statement.
• SELECT_statement has the following form (words in all caps are referred to as
clauses):
o SELECT selectList (contains a comma-delimited list of columns)
FROM TableName (name of the table containing the data)
WHERE searchClause (optional: contains logical statements correlating
columns and values)
ORDER BY orderExpression (optional: will sort by column and/or by
ASC|DESC)
• If selectList is "*", then all columns are obtained;
• When using multiple logical operators in the WHERE clause, use parenthesis.
Without parenthesis, note that NOT takes highest precedence, followed by AND,
followed by OR;
• When comparing strings in a WHERE clause, you must surround the variable you
are comparing the column to in single quotes;
• The LIKE operator can be used in the WHERE clause to search for patterns in
strings:
o % -Translates to any string of zero or more chars;
o _ -Translates to exactly one char;
o [] -Translates to any specific char within a certain range;
o For example: WHERE ColumnName LIKE 'M%' (this returns all items in
ColumnName that start with the letter "M"). WHERE ColumnName LIKE
'[a-f]ouse' (this returns all items with "a" through "f" as their first char,
and "ouse" as the rest);
• If the ORDER clause is placed before the WHERE clause, an error will result;
Back to Top
• If there is any likelihood that a database will be altered by more than one user
simultaneously, the locktype attribute of objRS.Open is important. Its default is
read-only, which prevents updates altogether. The four types are:
o adLockReadOnly;
o adLockPessimistic - Records are locked immediately on editing;
o adLockOptimistic - Records are only locked when the Update method is
called;
o adLockBatchOptimistic - Records are not locked until a batch update
occurs. This should be used with client-side cursors;
• The pessimistic lock is less efficient than the optimistic lock, but also safer. If
there will be many simultaneous updates to a table, use the pessimistic lock ("not
many" being defined as a user or two?);
• You can create a Recordset object implicitely using the Execute method of the
Connection object. You cannot specify the CursorType or LockType if you do
this. Set objRS = objConn.Execute(CommandText, RecordsAffected,
Options) Note that Options must be set to adCmdTable if CommandText is a
table name;
o *objConn.Execute SQLstatement can be used to insert, update, and
delete records from a database, without using a recordset;
• Runtime SQL statements (all the SQL queries performed prior to now in the
guide) are less efficient than stored procedures. Stored procedures are SQL
queries that have been stored by the database program, and which result in a
saved execution plan the first time the procedure is executed. That plan makes
future executions of the query much more efficient. The value of the Source
attribute in objRS.Open is the stored procedures name;
• To create a stored procedure in Microsoft SQL Server: Expand the Databases tab.
Expand the Database to which you want to add a stored procedure. Click the node
entitled "Stored Procedures." Right click in the right pane and select "New Stored
Procedure." Replace "[Procedure Name]" in the resulting dialog box with
whatever name you want. Type the SQL query you want to execute after the AS.
(Note - comments should be surround with /* and */, or with -- ) Click OK.
• To create a stored procedure in Access: Click the Query tab in the Objects
toolbar. Double click the "Create a Query" option. Select the table or tables you
are interested in generating a query for, and click close. Choose what fields you
want the query to return. Choose how you want the fields sorted. Close the Query
Design view, and click "yes" when asked to save. Enter a name for the query.
• To run a stored procedure: strSQL = "EXEC nameofprocedure " &
inputVariable...
• *The Command object, when used in conjunction with objConn.Execute, can be
used to retrieve return values from the database (through stored procedures). This
process is a bit involved; use an SP Wrapper to make it easier.
• The Command object can be used to implicitely create Recordsets as well. Its
Execute method operates like that of the Connection object. First, instantiate
objCommand, then set its ActiveConnection, CommandText, and CommandType
properties, then create/instantiate objRS (Set objRS = objCommand.Execute).
Back to Top
• External Notes:
o Collaboration Data Objets (CDO) - interacting with Exchange
CDONTS (a subset of CDO) is used to send and received simple
emails. The CDONTS.NewMail properties/methods are:
.Send - catch all method; takes from, to, subject, body, importance;