How to read a field from a database table using ASP and SQL Server.


Reading a field from a database table using ASP is not particlarly hard. As the following code demonstrates, it can be achieved in 10 lines of code or less (Not including the HTML which wraps around it). The code fragment shown, uses ASP to access a SQL Server database. The code changes required for the ASP to access other databases are not major undertakings - the lines that provide the programming challenge are lines 3 and 4. Please note, the line numbers are just shown for clarity. They are not actually part of the code.

1. <@ LANGUAGE="VBSCRIPT">
2. !-- #INCLUDE file="adovbs.inc" --

3. % Set oConn=Server.CreateObject("ADODB.Connection")

4. oConn.Open "SERVER=SERVERNAME;UID=UIDNUMBER;Password=PASSWORD;DRIVER=SQL Server;DATABASE=Database"
5. SQLStatement = "SELECT Table FROM Database WHERE Field_in_Table=1"
6. Set RS = oConn.Execute(SQLStatement)
7. number_of_fields = RS.FIELDS.COUNT
8. response.write RS("Table") ' Write out the contents of the field which has been selected %
9. % response.write number_of_fields
10. set oConn = Nothing %




www.cyberthinc.com