6
Active Server Pages/Database Access Using ADO Contents 1 Objectives 2 Content 2.1 Connecting to a Database 2.2 INSERT, UPDATE, and DELETE 2.3 SELECT 2.3.1 Retrieving the Recordset 2.4 Closing a Database Connection 2.5 ADO Constants 3 Summary 4 Review Questions 5 Exercises Objectives This describes database connectivity with ADO (ActiveX Data Objects) and how you can use this to communicate and manage a database server. You will learn how to open a connection to a database, run INSERT, UPDATE, DELETE, and SELECT statements as well as execute a stored procedure. Content Active Server Pages, being a scripted language, is a stateless language. By this, we mean that it doesn't preserve the state of the application between page loads. Nearly all ASP hosting solutions will include some sort of database hosting. Most common is MySQL, followed by Microsoft SQL Server. No matter what database you are using, ADO will allow you to manage the database through Active Server Pages. While it's true that you can store persistant data in the Application object. This is basically just stored in a memory cache that will be flushed whenever IIS or the server is restarted. It also causes problems when trying to create an application which will be used in a server cluster (where each cluster has its own version of the Application cache.) Connecting to a Database Here is a sample showing how to open a connection to a database. To do this, we call the Server.CreateObject to create an instance of the built-in ADODB Connection object. Not only is this used to create the initial connection to the database, it will also be used to create the Recordset and Command Objects later. You will need to replace the text mysqluser, mysqlpass, and mysqldbname with the correct values for your Active Server Pages/Database Access Using ADO - Wikibooks, open bo... http://en.wikibooks.org/wiki/Active_Server_Pages/Database_Access_Us... 1 of 6 3/27/2014 10:27 AM

Active Server Pages_Database Access Using ADO - Wikibooks, Open Books for an Open World

Embed Size (px)

DESCRIPTION

asp

Citation preview

  • Active Server Pages/Database Access Using ADO

    Contents

    1 Objectives2 Content

    2.1 Connecting to a Database2.2 INSERT, UPDATE, and DELETE2.3 SELECT

    2.3.1 Retrieving the Recordset2.4 Closing a Database Connection2.5 ADO Constants

    3 Summary4 Review Questions5 Exercises

    ObjectivesThis describes database connectivity with ADO (ActiveX Data Objects) and how you can use this tocommunicate and manage a database server. You will learn how to open a connection to a database, runINSERT, UPDATE, DELETE, and SELECT statements as well as execute a stored procedure.

    ContentActive Server Pages, being a scripted language, is a stateless language. By this, we mean that it doesn't preservethe state of the application between page loads. Nearly all ASP hosting solutions will include some sort ofdatabase hosting. Most common is MySQL, followed by Microsoft SQL Server. No matter what database youare using, ADO will allow you to manage the database through Active Server Pages.

    While it's true that you can store persistant data in the Application object. This is basically just stored in amemory cache that will be flushed whenever IIS or the server is restarted. It also causes problems when tryingto create an application which will be used in a server cluster (where each cluster has its own version of theApplication cache.)

    Connecting to a Database

    Here is a sample showing how to open a connection to a database. To do this, we call the Server.CreateObjectto create an instance of the built-in ADODB Connection object. Not only is this used to create the initialconnection to the database, it will also be used to create the Recordset and Command Objects later.

    You will need to replace the text mysqluser, mysqlpass, and mysqldbname with the correct values for your

    Active Server Pages/Database Access Using ADO - Wikibooks, open bo... http://en.wikibooks.org/wiki/Active_Server_Pages/Database_Access_Us...

    1 of 6 3/27/2014 10:27 AM

  • database. Note that this is accessing a MySQL server on the local server (localhost) using ODBC.

    ' create a connection objectSet oConnection = Server.CreateObject("ADODB.Connection") ' open a connection to a data sourceoConnection.Open "Driver={MySQL ODBC 3.51 Driver};server=localhost;port=3306;uid=mysqluser;pwd=mysqlpass;database=mysqldbname;

    Note that you could wrap this statement with an On Error block to trap any exceptions that may occur.

    INSERT, UPDATE, and DELETE

    The following will use the ADODB.Connection object to run an INSERT query on the database. The code isthe same whether you are doing INSERT, UPDATE, or DELETE. You only need to change the sQueryvariable with your modified query.

    ' build the query to runsQuery ="INSERT INTO Company VALUES ("Microsoft")" ' execute the insert statementoConnection.Execute sQuery, nRecordsAffected, adCmdText + adExecuteNoRecords Response.Write "Records Affected: " & nRecordsAffected

    The constants adCmdText and adExecuteNoRecords are described in the section ADO Constants.

    SELECT

    The following code can be used to run a SELECT statement against a database. You must first open aconnection to a database using the code described in the section Connecting to a Database.

    sQuery = "SELECT companyid, companyname FROM tblCompany" ' create the recordset object to hold the result setsSet rs = Server.CreateObject("ADODB.Recordset") ' set the number of records to fetch into memory at once (performance)rs.CacheSize = 256 ' execute the query and populate the recordset rs.Open sQuery, oConnection, adOpenKeySet, adLockReadOnly, adCmdText 'More examples of SELECT (based on criteria) are:'*example 1.sQuery = "SELECT companyid, companyname FROM tblCompany WHERE companyid = 1" '1. See details below

    1. When sQuery in above code snippet is set as example 1. it will fetch records with companyid havingvalue 1, in this SQL statement WHERE clause is used to define that criteria.

    Active Server Pages/Database Access Using ADO - Wikibooks, open bo... http://en.wikibooks.org/wiki/Active_Server_Pages/Database_Access_Us...

    2 of 6 3/27/2014 10:27 AM

  • The constants adOpenKeySet, adLockReadOnly, and adCmdText are described in the section ADOConstants. Now that you have opened a recordset, what can you do with it?

    Retrieving the Recordset

    The following code will show you how to use the recordset object (rs) described in the SELECT section toretrieve values from your database query.

    ' EOF checks for the end of a recordsetIf Not rs.EOF Then

    ' The Fields collection accesses fields from a single recordsFirstName = rs.Fields("firstname").Value

    ' You can enumerate all fields in the recordFor Each oFld In rs.fields

    Response.Write "Field = " & oFld.Name & ""Response.Write "Value = " & oFld.Value & ""

    NextEnd If ' You can also loop through all recordsDo Until rs.EOF

    Response.Write "Name = " & rs.Fields("firstname").Value & ""' make sure you don't forget this next step' MoveNext will move to the next record in the resultsetrs.MoveNext

    Loop ' following is always a good idea to clean up resources ASAPrs.Close : rs = 0

    Closing a Database Connection

    You should always close your database connection when you are done accessing the database. It is not required,but it is always a good idea.

    ' it's a good idea to close your recordset first (if necessary)rs.Close : rs = 0 ' this will close the database connection oConnection.Close

    ADO Constants

    Variable Purpose

    'adOpenKeySet

    Open a keyset

    Const adOpenKeySet = 1

    Active Server Pages/Database Access Using ADO - Wikibooks, open bo... http://en.wikibooks.org/wiki/Active_Server_Pages/Database_Access_Us...

    3 of 6 3/27/2014 10:27 AM

  • adLockReadOnly

    Create a database lock for read only access to a table. This is a forward-only cursorwhich provides the most efficient method for retrieving results.

    Const adLockReadOnly = 1

    adLockPessimistic

    This locking method will lock a database record as soon as edits have been made tothe database. (Not really used in Active Server Pages)

    Const adLockPessimistic = 2

    adLockOptimistic

    Use optimistic record locking on the database records. Meaning a record will only belocked when records have been modified and edits are committed back to thedatabase. (Not really used in Active Server Pages)

    Const adLockOptimistic = 3

    adCmdText

    Indicates the SQL command being passed is text (an SQL statement)

    Const adCmdText = 1

    adCmdTable

    Indicates the SQL command being passed is the name of a database table to open (allrows and fields)

    Const adCmdTable = 2

    adCmdStoredProc

    Indicates the SQL command being passed is the name of a stored procedure toexecute. When using this call, the parameters must be defined separately.

    Const adCmdStoredProc = 4

    adCmdUnknown

    Indicates the SQL command being passed is unknown - the ADO library will do it'sbest to interpret what type of command was intended.

    Const adCmdUnknown = 8

    adStateOpen

    Indicates the current state of the result set. This indicates the recordset is open anddata retrieval operations can be performed.

    Const adStateOpen = 1

    Active Server Pages/Database Access Using ADO - Wikibooks, open bo... http://en.wikibooks.org/wiki/Active_Server_Pages/Database_Access_Us...

    4 of 6 3/27/2014 10:27 AM

  • adStateClosed

    Indicates the current state of the result set. This indicates the recordset is closed anddata retrieval are forbidden.

    Const adStateClosed = 0

    adExecuteNoRecords

    Indicate that no recordset is returned. SQL command is stored procedure call, INSERT,UPDATE, or DELETE statement.

    Const adExecuteNoRecords = 128

    adParamInput

    Stored procedure parameter is an input (this is the default) meaning we are justpassing data into the procedure.

    Const adParamInput = 1

    adParamOutput

    Stored procedure parameter is an output meaning that data will be returned by theprocedure.

    Const adParamOutput = 2

    adParamInputOutput

    Stored procedure parameter is both an input and an output. Data is passed into theprocedure and then returned after execution is complete.

    Const adParamInputOutput = 3

    adParamReturnValue

    Indicates that the variable holds the return value from a procedure

    Const adParamReturnValue = 4

    adVarChar

    Variable character (string) SQL data type

    Const adVarChar = 200

    adChar

    Fixed length character SQL data type

    Const adChar = 129

    adInteger

    Integer SQL data type

    Const adInteger = 3

    Active Server Pages/Database Access Using ADO - Wikibooks, open bo... http://en.wikibooks.org/wiki/Active_Server_Pages/Database_Access_Us...

    5 of 6 3/27/2014 10:27 AM

  • adCurrency

    Currency SQL data type

    Const adCurrency = 6

    SummaryUsing ADODB is the ideal way to connect to a database through Active Server Pages. ADODB utilizes ODBCor OLE DB technologies to connect to a database depending on the connection string you use when using theADODB.Connection::Open method. The most efficient method of access is OLE DB.

    You may choose to create a database library code to simplify the task of working with a database. You cancreate a database class which manages all the tasks of communicating with a database. Combine this withdatabase configuration settings stored in a global.asa file, and you will have a quick yet powerful way ofexecuting database queries.

    Make sure to make use of the ADO Constants to make the most efficient use of the ADO methods and yourdatabase server. The examples above should give you everything you need to work with a database.

    Review QuestionsWhat does ADO stand for?Which object is used to connect to a database?What method do you use to connect to a database?Which object do you need to retrieve results from SELECT?How do you retrieve the value of a field from the current record?How do you enumerate all fields from a recordHow do you close a connection to a database

    ExercisesWrite the code to run an INSERT, UPDATE, or DELETE queryWrite the code to execute a stored procedure?Write the code to execute a SELECT statement and read its results

    Retrieved from "http://en.wikibooks.org/w/index.php?title=Active_Server_Pages/Database_Access_Using_ADO&oldid=2611709"

    This page was last modified on 24 February 2014, at 20:54.Text is available under the Creative Commons Attribution/Share-Alike License; additional terms mayapply. By using this site, you agree to the Terms of Use and Privacy Policy.

    Active Server Pages/Database Access Using ADO - Wikibooks, open bo... http://en.wikibooks.org/wiki/Active_Server_Pages/Database_Access_Us...

    6 of 6 3/27/2014 10:27 AM