Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving...

27
Database Connectivity Database Connectivity Session 2 Session 2
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    222
  • download

    2

Transcript of Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving...

Page 1: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Database ConnectivityDatabase Connectivity

Session 2Session 2

Page 2: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Topics CoveredTopics Covered

ADO Object ModelADO Object Model

Database ConnectionDatabase Connection

Retrieving Records Retrieving Records

Creating HTML Documents Creating HTML Documents on-the-flyon-the-fly

Page 3: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Database AccessDatabase Access

ASP provides easy access to databasesASP provides easy access to databases

It contains Database Access ComponentIt contains Database Access Component

Contains ActiveX Data Objects (ADO) Contains ActiveX Data Objects (ADO) – Object ModelObject Model– ADO methods to manipulate databases and ADO methods to manipulate databases and

build dynamic pagesbuild dynamic pages

ADO can use ODBC interface to RDBs. ADO can use ODBC interface to RDBs.

ADO can also use other interfaces – OLE-ADO can also use other interfaces – OLE-DB Provider DB Provider

Page 4: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

ADO Object ModelADO Object Model

Connection Object

Recordset ObjectFields Collection

Field Object

Properties Collection

Property Object

Command ObjectParameters Collection

Parameter Object

Properties Collection

Property Object

Properties Collection

Property Object

Errors Collection

Error Object

Page 5: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

ADO ObjectsADO ObjectsConnection ObjectConnection Object– Establish active connection to gain access to data Establish active connection to gain access to data

Command ObjectCommand Object– Used to execute SQL queries or manipulate data directlyUsed to execute SQL queries or manipulate data directly

Recordset ObjectRecordset Object– Gives us access to data that is returned from executing Gives us access to data that is returned from executing

the SQL query, a stored procedure, or by opening the tablethe SQL query, a stored procedure, or by opening the table

Properties CollectionProperties Collection– Collection of Properties for Connection, Command, and Collection of Properties for Connection, Command, and

Recordset objectsRecordset objects

Fields CollectionFields Collection– Individual fields (values) within each recordIndividual fields (values) within each record

Page 6: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Connecting to Data SourcesConnecting to Data Sources

Before connecting to a data store, we need to Before connecting to a data store, we need to specify what it is and where it isspecify what it is and where it isThree ways to supply this information when Three ways to supply this information when creating the connection:creating the connection:– Connection StringConnection String

Simple character string that lists all of the information Simple character string that lists all of the information needed to connect to a data sourceneeded to connect to a data source

– Data Link FilesData Link FilesCreate a Universal Data Link (UDL) file that stores the info.Create a Universal Data Link (UDL) file that stores the info.

– Data Source Names (DSN)Data Source Names (DSN)Use ODBC drivers to set up the DSNUse ODBC drivers to set up the DSNNow considered as outdated approach – OLE-DB provider is Now considered as outdated approach – OLE-DB provider is considered better because of efficiencyconsidered better because of efficiency

Page 7: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Connection StringConnection StringA typical connection string will contains some or A typical connection string will contains some or all of the following key pieces of informationall of the following key pieces of information– Provider:Provider: the type of OLE-DB provider used in the connectionthe type of OLE-DB provider used in the connection

– Driver:Driver: type of ODBC driver used if not using OLE-DB providertype of ODBC driver used if not using OLE-DB provider

– Initial File NameInitial File Name or or Data Source:Data Source: the physical database path the physical database path and the file nameand the file name

– Initial Catalog:Initial Catalog: the name of the databasethe name of the database

– User ID:User ID: the user name needed to connect to the databasethe user name needed to connect to the database

– Password:Password: the password for the specified userthe password for the specified user

– Persist Security Info:Persist Security Info: a boolean variable set to TRUE if you a boolean variable set to TRUE if you want windows to remember the passwordwant windows to remember the password

Page 8: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Examples of Connection StringExamples of Connection String

For Access DatabaseFor Access Database

MS Access uses the Microsoft Jet Engine, so the MS Access uses the Microsoft Jet Engine, so the OLE-DB provider is specified as the Jet EngineOLE-DB provider is specified as the Jet EngineIf we are accessing the same database using the If we are accessing the same database using the ODBC driver for MS Access (instead of the OLE-DB ODBC driver for MS Access (instead of the OLE-DB provider), we use the following:provider), we use the following:

For SQL Server database, the connect string may For SQL Server database, the connect string may look like:look like:

““Provider = Microsoft.Jet.OLEDB.4.0;” & _Provider = Microsoft.Jet.OLEDB.4.0;” & _““Data Source = c:\mydatabases\test.mdb;” & _Data Source = c:\mydatabases\test.mdb;” & _““Persist Security Info = False”Persist Security Info = False”

““Driver = {Microsoft Access Driver (*.mdb)};” & _Driver = {Microsoft Access Driver (*.mdb)};” & _““DBQ = c:\mydatabases\test.mdb”DBQ = c:\mydatabases\test.mdb”

““Provider = SQLOLEDB; Persist Security Info = False;” & _Provider = SQLOLEDB; Persist Security Info = False;” & _““User ID = joe; Password = shmoe;” & _User ID = joe; Password = shmoe;” & _““Initial File Name = c:\mydatabases\test.mdf”Initial File Name = c:\mydatabases\test.mdf”

Page 9: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

DSN-less Connection StringDSN-less Connection String

Make a folder called db in your web folder Make a folder called db in your web folder Put your database into the db folder you just Put your database into the db folder you just created.  created.  Use the following connection string in your Use the following connection string in your ASP code:ASP code:

set objConn= Server.CreateObject("ADODB.Connection")set objConn= Server.CreateObject("ADODB.Connection")objConn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; _ objConn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; _ DBQ= " & DBQ= " & server.mappath("db/DBName.mdb")server.mappath("db/DBName.mdb")

   Modify the DBName.mdb to match your Modify the DBName.mdb to match your actual database name.actual database name.

Page 10: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Connection ObjectConnection Object

Create an instance of connection objectCreate an instance of connection object– set myconn=Server.CreateObject(“ADODB.Connection”) set myconn=Server.CreateObject(“ADODB.Connection”)

Scope of ConnectionScope of Connection– Create the connection every time you access the dataCreate the connection every time you access the data– Create the connection once and use it for different Create the connection once and use it for different

operationsoperations

Connection creation statement can be placed in the Connection creation statement can be placed in the Session_onStart or Application_onStart routines in Session_onStart or Application_onStart routines in global.asaglobal.asa

Connection object contains methods and properties Connection object contains methods and properties to open, and close connections, execute commands to open, and close connections, execute commands on the data source specified in the connection, and on the data source specified in the connection, and controlling transactions.controlling transactions.

Page 11: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Methods of Connection ObjectMethods of Connection Object

OpenOpen Opens a new connection to a data sourceOpens a new connection to a data source

CloseClose Closes an existing open connectionCloses an existing open connection

ExecuteExecute Execute a query, SQL statement or stored Execute a query, SQL statement or stored procedureprocedure

BeginTransBeginTrans Begins a new transactionBegins a new transaction

CommitTransCommitTrans Saves any changes made and ends the Saves any changes made and ends the transaction. May also start a new transaction transaction. May also start a new transaction

RollbackTransRollbackTrans Cancels any changes made and ends the Cancels any changes made and ends the transaction. May also start a new transaction transaction. May also start a new transaction

OpenSchemaOpenSchema For server side scripts, allows the view of For server side scripts, allows the view of database schema, such as tables, columns, database schema, such as tables, columns,

etc.etc.

Page 12: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Command ObjectCommand Object

Command object can be used to directly Command object can be used to directly execute commandsexecute commandsIt provides methods and properties to It provides methods and properties to manipulate individual commands.manipulate individual commands.MethodsMethods– CreateParameterCreateParameter– ExecuteExecute

PropertiesProperties– ActiveConnection, CommandText, Command ActiveConnection, CommandText, Command

Timeout, CommandType, Name, Prepared, Timeout, CommandType, Name, Prepared, StateState

Page 13: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

RecordSet ObjectRecordSet Object

Contains query resultsContains query resultsSyntaxSyntaxset myset = connection.execute(CommandText, set myset = connection.execute(CommandText,

RecordsAffected, Options)RecordsAffected, Options)set myset = command.execute(RecordsAffected, Parameters, set myset = command.execute(RecordsAffected, Parameters,

Options)Options)

ExampleExampleset mycon=server.createobject(“ADODB.Connection”)set mycon=server.createobject(“ADODB.Connection”)

mycon.open “Northwind” “System DSN”mycon.open “Northwind” “System DSN”set myset = mycon.execute(“select * from set myset = mycon.execute(“select * from

products”)products”)

Page 14: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

RecordSet Object (Continued)RecordSet Object (Continued)

The ADO Recordset object is used to hold a set of The ADO Recordset object is used to hold a set of records from a database tablerecords from a database table

A Recordset object consist of records and A Recordset object consist of records and columns (fields)columns (fields)

Most important and the most used object to Most important and the most used object to manipulate data from a databasemanipulate data from a database

When you first open a Recordset, the When you first open a Recordset, the current current record pointerrecord pointer will point to the first record and will point to the first record and the BOF and EOF properties are False. the BOF and EOF properties are False.

If there are no records, the BOF and EOF property If there are no records, the BOF and EOF property are True.are True.

Page 15: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

RecordSet Object (Continued)RecordSet Object (Continued)

BOF

EOF

RecordSetObject

(say MyRs)

First Record

Last Record

FieldsCollection

0 1 2 3 4

MyRs.fields.count will return 5MyRs(0).Name returns the name of the first fieldMyRs(0).Value returns the value of the first field

Current RecordPointer

When the recordset object is created, the CurrentRecord Pointer will be pointing to the First Recordand BOF and EOF properties will be FalseIf the recordset is empty, BOF and EOF will be True

Page 16: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Methods of RecordSet ObjectMethods of RecordSet Object

AddNewAddNew – – Creates a new record in an updatable recordsetCreates a new record in an updatable recordset

CancelBatchCancelBatch – – Cancels a pending batch updateCancels a pending batch update

CancelUpdateCancelUpdate – – Cancels any changes made to the current Cancels any changes made to the current or new recordor new record

CloneClone – – creates a duplicate of the current recordsetcreates a duplicate of the current recordset

CloseClose – – closes an open recordset and any dependent objectscloses an open recordset and any dependent objects

DeleteDelete – – deletes the current record in an open recordsetdeletes the current record in an open recordset

GetRowsGetRows – Extract a number of rows into an array – Extract a number of rows into an arrayMoveMove – – Moves the cursor forward or backward by specified Moves the cursor forward or backward by specified number of recordsnumber of records

Example: move(5) – moves the cursor forward by 5 recordsExample: move(5) – moves the cursor forward by 5 records

move(-3) – moves the cursor backward by 3 records move(-3) – moves the cursor backward by 3 records

Page 17: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Methods of RecordSet Object (contd.)Methods of RecordSet Object (contd.)

MoveFirst, MoveLast, MoveNext, MoveFirst, MoveLast, MoveNext, MovePreviousMovePrevious– Moves to the first, last, next, or previous record in the Moves to the first, last, next, or previous record in the

recordset, and makes that the current recordrecordset, and makes that the current record

NextRecordsetNextRecordset – – Move to the next recordset in the queryMove to the next recordset in the query

OpenOpen – – Opens a curser on a recordsetOpens a curser on a recordset

RequeryRequery – – Updates data by re-executing the original queryUpdates data by re-executing the original query

ResyncResync – – Refreshes the data, but does not re-execute the Refreshes the data, but does not re-execute the query. This allows updates to be seen but no new rows.query. This allows updates to be seen but no new rows.

SupportsSupports – – Determines whether the recordset supports Determines whether the recordset supports certain functionscertain functions

Update Update – – Saves any changes made to the current recordSaves any changes made to the current record

UpdateBatchUpdateBatch – – Writes all pending batch updates to disk.Writes all pending batch updates to disk.

Page 18: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

ExamplesExamples

Example 1 - Get all the customersExample 1 - Get all the customers

Example 2 – Get products with CategoryID = 3Example 2 – Get products with CategoryID = 3

Example 3 - Retrieve data based on user inputExample 3 - Retrieve data based on user input

Page 19: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Example 1 Code (customers_new.asp)Example 1 Code (customers_new.asp)<HTML><HEAD><TITLE>Results</TITLE></HEAD><BODY BGCOLOR=cyan><%@ LANGUAGE="VBSCRIPT"%>

<%SQL = "SELECT * FROM CUSTOMERS;“

SET DbObj = Server.CreateObject("ADODB.CONNECTION")

myvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & _ server.mappath("db_f03/Northwind.mdb")

DbObj.Open myvar

SET oRs = DbObj.Execute(SQL)%>

(continued in next slide)

Define a simple sql statement

create an instance of the connection object

Construct the DSN-less connection string

Open the connection to the data source

execute the sql string and store the results in the recordset object

Notice the continuation character ( _ )

Page 20: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Example 1 Code (Continued)Example 1 Code (Continued)<h1>Customer Information</h1><TABLE BORDER=3><TR><TD><b><center>CustomerID</b></center></TD> <TD><b><center>CompanyName</b></center></TD><TD><b><center>ContactName</b></center></TD><TD><b><center>Address</b></center></TD></TR>

<% WHILE NOT oRs.EOF %><TR> <TD> <%= oRs.Fields("CUSTOMERID").Value %> </TD> <TD> <%= oRs.Fields("COMPANYNAME").Value %> </TD> <TD> <%= oRs.Fields("CONTACTNAME").Value %> </TD> <TD> <%= oRs.Fields("ADDRESS").Value %> </TD> </TR> <% oRs.MoveNext %><% WEND %></TABLE>

</BODY></HTML>

Create a Table. Hard code the attribute names in the first row

while the recordset is not empty

Add the value of each attribute intoHTML table using the <%= operator

Move the cursor to the nextavailable record

End of the while loop

Page 21: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Example 2 Code (products_new.asp)Example 2 Code (products_new.asp)<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><meta name="GENERATOR" content="Microsoft FrontPage 4.0"><meta name="ProgId" content="FrontPage.Editor.Document"><title>New Page 1</title></head><body><h1>Products with Category ID 3</h1><%set my_conn= Server.CreateObject("ADODB.Connection")

myvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & server.mappath("db_f03/Northwind.mdb")

my_conn.Open myvar

StrSql= "Select * from products where CategoryID = 3"set MyRs = my_conn.Execute (StrSql)

if MyRs.BOF or MyRs.EOF then response.write "ah, yeah: That didn't work.<br>There was an error. your gonna hafta to go " & _ "ahead, and ah, try again.<a href=javascript:history.back();>back</a> okay? thanks a lot." response.endend if%>

Establish connection with the nortwind database

Construct the DSN-less connection string

Open the connection to the data source

From the products table, retrieve the products with categoryid=3 and store the records in the MyRs recordset object

If no records found are found, i.e., theRecordset object is empty, then sendthe user back to the previous page

Page 22: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Example 2 Code (Continued)Example 2 Code (Continued)<p><br><table border =1 width="100%"><tr> <% howmanyfields=MyRs.fields.count for i=0 to howmanyfields-1 %> <td><b><font color = "darkblue"><%= MyRs(i).name %></font></b></td> <% next %></tr> <% do while not MyRs.eof %><tr><% for I = 0 to howmanyfields-1

cur_field = MyRs(I).value %> <td valign=top><%= cur_field %></td> <% next %> </tr> <%MyRs.movenext loop%> <!-- end of do while loop -->

<%MyRs.close Set MyRs= Nothing My_Conn.Close set My_Conn=nothing%> <br></table></body></html>

Now, go through the record set and create the HTML Table

Get the field count

Now, go through each record and print out the values of each field. Start with the first record. Within each record,for each field get its value and store it in the variable

Output the value of the variableinto the table data element

Move the record pointerto the next record

Close the recordset and the connection and set them to nothing

Output the field names for the first row

Page 23: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Example 3 Code (select_new.asp)Example 3 Code (select_new.asp)<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>Get Product from Form</title> </head> <% 'Establish the connection with the nowrthwind databaseset my_conn= Server.CreateObject("ADODB.Connection")

'Construct the connection string using relative path for the database filemyvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & server.mappath("db_f03/Northwind.mdb")

'Open the connection to the data sourcemy_conn.Open myvar

'Get the products from the products_new tableStrSql= "Select * from products" set rs = my_conn.Execute (StrSql)

'Display a message if no products foundif rs.BOF or rs.EOF then ' No records found response.write "Hmm... That didn't work.<br>There was an error. " & _ "Oh well, try again.<a href=javascript:history.back();>back</a>" response.end end if %>

Page 24: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Example 3 Code Continued (select_new.asp)Example 3 Code Continued (select_new.asp)<body> <h1>Available Products..</h1><h2>Please select a product and click on Submit Query to get more information.</h2><!-- Create a select object with product ids from the retrieved tuples --><!-- From that list the user can select a particular product --><!-- When the user clicks on the submit button, the form, along with its data, --><!-- is sent as input to the get_product_new.asp file -->

<form method="post" action="get_product_new.asp"> <!-- call the next ASP page -->Select Product:<select name="product"> <!– creating the drop down list --><%do while not rs.eof%> <option value="<%=rs("productid")%>"><%=rs("productname")%></option> <% rs.movenext 'move the cursor to the next record in the recordsetloop

my_Conn.Close ‘close th e connection objectset my_conn = nothing%>

<input type="submit"></form></body></html>

Page 25: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Example 3 Code (get_product_new.asp)Example 3 Code (get_product_new.asp)

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>Get Product from Form</title> </head> <% if request.form("product")="" then response.write "You must select a product in <a href=""select_new.asp"">select_new.asp</a> first." response.endend if'Establish the connection with the nowrthwind databaseset my_conn= Server.CreateObject("ADODB.Connection")'Construct the connection string using relative path for the database filemyvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & server.mappath("db_f03/Northwind.mdb")'Open the connection to the data sourcemy_conn.Open myvar'Construct the SQL statement by concatenating the value selected by the userStrSql= "Select * from products where productid=" & request.form("product")'Execute the SQL statement and create a recordsetset rs = my_conn.Execute (StrSql) 'Display a message if no products foundif rs.BOF or rs.EOF then ' No records found response.write "Hmm... That didn't work.<br>There was an error. Oh well, " & _ "try again.<a href=javascript:history.back();>back</a>" response.end end if %>

Page 26: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Example 3 Code Continued (get_product_new.asp)Example 3 Code Continued (get_product_new.asp)<body> <h1>Information about the " <%=rs("productname")%> " product:</h1> <table border="1"> <!-- Create the first row of the table with headings --><tr><td>Product ID</td><td>Product Name</td><td>Supplier ID</td><td>Quantity Per Unit</td> <td>Price</td><td>Units in Stock</td></tr>

<% do while not rs.eof %> <!-- Display the information corresponding to the selected product --> <tr><td><%=rs("productid")%> </td><td><%=rs("productname")%></td> <td><%=rs("supplierid")%></td><td> <%=rs("QuantityPerUnit")%></td> <td><%=rs("UnitPrice")%></td><td><%=rs("unitsinstock")%> </td></tr>

<% rs.movenext loop 'End of do while loop

my_Conn.Close ‘Close the connection objectset my_conn = nothing %>

</table></body> </html>

Page 27: Database Connectivity Session 2. Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly.

Assignment 2Assignment 2

Create two asp pages.Create two asp pages.

The first asp page should list the Company The first asp page should list the Company names in a drop-down list. The user can names in a drop-down list. The user can select a Company and click on the submit select a Company and click on the submit button. It should call the next asp page button. It should call the next asp page which lists the Company information as well which lists the Company information as well as the sponsorship informationas the sponsorship informationDatabase to be used: Database to be used: exercise2.mdbexercise2.mdb

Tables to be used: Tables to be used: Company and ProjectsCompany and Projects

Click to see the assignment demoClick to see the assignment demo