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

Slides:



Advertisements
Similar presentations
Basics of Database Programming with VB6
Advertisements

ADO DB in Access VBA © Walter Milner 2005 Slide: 1 ADO VBA Programming in Access.
Connecting to Database 21 Feb Database Options Can use many different databases in conjunction with php. – MySql; MS Access; Oracle; etc etc Most.
Mark Dixon Page 1 17 – Persistent data storage: relational databases and ADO.
1 Chapter 12 Working With Access 2000 on the Internet.
Session 6 Server-side programming - ASP. An ASP page is an HTML page interspersed with server-side code. The.ASP extension instead of.HTM denotes server-side.
ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet.
The ADO Data Control. Universal Data Access Open Database Connectivity (ODBC) –standard for accessing data in databases OLE-DB –allows access to data.
ActiveX Data Object ISYS 562. ADO An ActiveX control ActiveX is build upon COM, a contract that defines a standard interface by which objects communicate.
Using Objects and Properties
1 Active Server Pages Active Server Pages (ASPs) are Web pages ASP = server-side scripts + HTML The appearance of an Active Server Page depends on who.
VB.NET Database Access ISYS 812. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Copyright 2003 : Ismail M.Romi, PPU. All Rights Reserved 1 Lab10 Interacting with Data (Database Management)
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
CHAPTER 9 DATABASE MANAGEMENT © Prepared By: Razif Razali.
4-1 INTERNET DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
Chapter 7 PHP Interacts with Ms. Access (Open DataBase Connectivity (ODBC))
ActiveX Data Object (ADO) in JavaScript J.L.Wang, Yen-Cheng Chen Dept. of Infomation Management Ming-Chuan University Jan
© 2006 ITT Educational Services Inc. Course Name: IT390 Business Database Administration Unit 9 Slide 1 IT 390 Business Database Administration Unit 9:
Introduction to ADO By David R. Stevenson Consulting Software Engineer ABB Automation.
Database 20/2/12 Connection. 
Server Side Programming ASP1 Server Side Programming Database Integration (cont.) Internet Systems Design.
Irwin/McGraw-Hill Copyright© 2000 by the McGraw-Hill Companies, Inc. PowerPoint® Presentation to accompany prepared by James T. Perry University of San.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Using Visual Basic 6.0 to Create Web-Based Database Applications
Database actions In this presentation… –database actions –database connections –recordsets.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
McGraw-Hill/Irwin Programming in Visual Basic 6.0 © 2002 The McGraw-Hill Companies, Inc. All rights reserved. Update Edition Chapter 11 Accessing Database.
Mark Dixon Page 1 23 – Web applications: Writing data to Databases using ASP.
Web Server Administration Chapter 7 Installing and Testing a Programming Environment.
Copyright © 2001 by Wiley. All rights reserved. Chapter 9: Introduction to Working with Databases in Visual Basic Database Concepts Relational Database.
Tutorial 10 by Sam ine1020 Introduction to Internet Engineering 1 Database & Server-side Scripting Tutorial 10.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
Lecture Note 10: Simple Database Techniques. Introduction –Database System –Access, SQL Server and others. –Microsoft Access - Interacting with this databases.
Visual Basic ADO Programming 56:150 Information System Design.
CSCI 6962: Server-side Design and Programming Database Manipulation in ASP.
What is database?  Any Method for access info into Application from DataBase?  ODBC is standard for Accessing Data.  Problem with ODBC:  Information.
USING XML AS A DATA SOURCE. Data binding is a process by which information in a data source is stored as an object in computer memory. In this presentation,
How to Connect to Database ODBC (Open Database Connectivity) ADO (ActiveX Data Object) ASP Code To Connect to Database Recordset Object Navigating through.
Microsoft Access 2000 Presentation 1 The Basics of Access.
ActiveX Data Objects (ADO) is Microsoft’s latest database object model. The goal of ADO is to allow VB developers to use a standard set of objects to refer.
Tutorial 91 Databases A database is an organized collection of related information stored in a file on a disk A database allows companies to store information.
ASP. What is ASP? ASP stands for Active Server Pages ASP is a Microsoft Technology ASP is a program that runs inside IIS IIS stands for Internet Information.
ASP-12-1 Data Store Access Colorado Technical University IT420 Tim Peterson.
Lab 8 Data Access Using Microsoft ActiveX Data Object (ADO)
Database Access Using JDBC BCIS 3680 Enterprise Programming.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Database Connectivity What is ADO. What is ADO? ADO is a Microsoft technology ADO stands for ActiveX Data Objects ADO is a Microsoft Active-X component.
ASP-2-1 SERVER AND CLIENT SIDE SCRITPING Colorado Technical University IT420 Tim Peterson.
Source = Table rsObject.Open tablename, Connection Object, CursorType, LockType, adCmdTable Source = Stored Procedure rsObject.Open stored procedure name,
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 6: Accessing a database with PHP Rob Gleasure robgleasure.com.
7-1 Active Server and ADO Colorado Technical University IT420 Tim Peterson.
ASP-13-1 Recordsets Colorado Technical University IT420 Tim Peterson.
January 27, 2001Database Tutorial1 Using a Database in ASP.
1 ADO Activex Data Objects. 2 ADO ADO allows users to access data easily from many existing databases (such as Access or Paradox) From ODBC compliant.
Using databases ActiveX Data Objects (ADO) Connecting to a database Reading data from a database Inserting, updating and deleting records Using databases.
Chapter 5 Building Your Product Catalog database Objectives Create Database. Create Table. Connect to Database. Use ASP Script to add new products. Use.
Generating XML Data from a Database Eugenia Fernandez IUPUI.
 2 Data Object Library approaches ◦ DAO (Data Access Objects)  Original access strategy (up to VB6)  Closely linked to MS Access ◦ ADO (ActiveX Data.
ASP.NET Programming with C# and SQL Server First Edition
Data Access Objects .
INT213 Updating the Database.
VISUAL BASIC INTRODUCTION TO DATA CONNECTIVITY.
Chapter 10 ASP and Data Store Access
Database Objects 1/12/2019 See scm-intranet.
Chapter 10 ADO.
Presentation transcript:

Database Connectivity Session 2

Topics Covered ADO Object Model Database Connection Retrieving Records Creating HTML Documents on-the-fly

Database Access ASP provides easy access to databases It contains Database Access Component Contains ActiveX Data Objects (ADO) –Object Model –ADO methods to manipulate databases and build dynamic pages ADO can use ODBC interface to RDBs. ADO can also use other interfaces – OLE- DB Provider

ADO Object Model Connection Object Recordset Object Fields Collection Field Object Properties Collection Property Object Command Object Parameters Collection Parameter Object Properties Collection Property Object Properties Collection Property Object Errors Collection Error Object

ADO Objects Connection Object –Establish active connection to gain access to data Command Object –Used to execute SQL queries or manipulate data directly Recordset Object –Gives us access to data that is returned from executing the SQL query, a stored procedure, or by opening the table Properties Collection –Collection of Properties for Connection, Command, and Recordset objects Fields Collection –Individual fields (values) within each record

Connecting to Data Sources Before connecting to a data store, we need to specify what it is and where it is Three ways to supply this information when creating the connection: –Connection String Simple character string that lists all of the information needed to connect to a data source –Data Link Files Create a Universal Data Link (UDL) file that stores the info. –Data Source Names (DSN) Use ODBC drivers to set up the DSN Now considered as outdated approach – OLE-DB provider is considered better because of efficiency

Connection String A typical connection string will contains some or all of the following key pieces of information –Provider: the type of OLE-DB provider used in the connection –Driver: type of ODBC driver used if not using OLE-DB provider –Initial File Name or Data Source: the physical database path and the file name –Initial Catalog: the name of the database –User ID: the user name needed to connect to the database –Password: the password for the specified user –Persist Security Info: a boolean variable set to TRUE if you want windows to remember the password

Examples of Connection String For Access Database MS Access uses the Microsoft Jet Engine, so the OLE-DB provider is specified as the Jet Engine If we are accessing the same database using the ODBC driver for MS Access (instead of the OLE- DB provider), we use the following: For SQL Server database, the connect string may look like: “Provider = Microsoft.Jet.OLEDB.4.0;” & _ “Data Source = c:\mydatabases\test.mdb;” & _ “Persist Security Info = False” “Driver = {Microsoft Access Driver (*.mdb)};” & _ “DBQ = c:\mydatabases\test.mdb” “Provider = SQLOLEDB; Persist Security Info = False;” & _ “User ID = joe; Password = shmoe;” & _ “Initial File Name = c:\mydatabases\test.mdf”

DSN-less Connection String Make a folder called db in your web folder Put your database into the db folder you just created. Put your database into the db folder you just created. Use the following connection string in your ASP code: set objConn= Server.CreateObject("ADODB.Connection") objConn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; _ DBQ= " & server.mappath("db/DBName.mdb") Use the following connection string in your ASP code: set objConn= Server.CreateObject("ADODB.Connection") objConn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; _ DBQ= " & server.mappath("db/DBName.mdb") Modify the DBName.mdb to match your actual database name.

Connection Object Create an instance of connection object –set myconn=Server.CreateObject(“ADODB.Connection”) Scope of Connection –Create the connection every time you access the data –Create the connection once and use it for different operations Connection creation statement can be placed in the Session_onStart or Application_onStart routines in global.asa Connection object contains methods and properties to open, and close connections, execute commands on the data source specified in the connection, and controlling transactions.

Methods of Connection Object Open Opens a new connection to a data source Close Closes an existing open connection Execute Execute a query, SQL statement or stored procedure BeginTrans Begins a new transaction CommitTrans Saves any changes made and ends the transaction. May also start a new transaction RollbackTrans Cancels any changes made and ends the transaction. May also start a new transaction OpenSchema For server side scripts, allows the view of database schema, such as tables, columns, etc.

Command Object Command object can be used to directly execute commands It provides methods and properties to manipulate individual commands. Methods –CreateParameter –Execute Properties –ActiveConnection, CommandText, Command Timeout, CommandType, Name, Prepared, State

RecordSet Object Contains query results Syntax set myset = connection.execute(CommandText, RecordsAffected, Options) set myset = command.execute(RecordsAffected, Parameters, Options) Example set mycon=server.createobject(“ADODB.Connection”) mycon.open “Northwind” “System DSN” set myset = mycon.execute(“select * from products”)

RecordSet Object (Continued) The ADO Recordset object is used to hold a set of records from a database table A Recordset object consist of records and columns (fields) Most important and the most used object to manipulate data from a database When you first open a Recordset, the current record pointer will point to the first record and the BOF and EOF properties are False. If there are no records, the BOF and EOF property are True.

RecordSet Object (Continued) BOF EOF RecordSet Object (say MyRs) First Record Last Record Fields Collection MyRs.fields.count will return 5 MyRs(0).Name returns the name of the first field MyRs(0).Value returns the value of the first field Current Record Pointer When the recordset object is created, the Current Record Pointer will be pointing to the First Record and BOF and EOF properties will be False If the recordset is empty, BOF and EOF will be True

Methods of RecordSet Object AddNew – Creates a new record in an updatable recordset CancelBatch – Cancels a pending batch update CancelUpdate – Cancels any changes made to the current or new record Clone – creates a duplicate of the current recordset Close – closes an open recordset and any dependent objects Delete – deletes the current record in an open recordset GetRows – Extract a number of rows into an array Move – Moves the cursor forward or backward by specified number of records Example: move(5) – moves the cursor forward by 5 records Example: 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

Methods of RecordSet Object (contd.) MoveFirst, MoveLast, MoveNext, MovePrevious –Moves to the first, last, next, or previous record in the recordset, and makes that the current record NextRecordset – Move to the next recordset in the query Open – Opens a curser on a recordset Requery – Updates data by re-executing the original query Resync – Refreshes the data, but does not re-execute the query. This allows updates to be seen but no new rows. Supports – Determines whether the recordset supports certain functions Update – Saves any changes made to the current record UpdateBatch – Writes all pending batch updates to disk.

Examples Example 1 - Get all the customers Example 1 - Get all the customers Example 2 – Get products with CategoryID = 3 Example 2 – Get products with CategoryID = 3 Example 3 - Retrieve data based on user input Example 3 - Retrieve data based on user input

Example 1 Code (customers_new.asp) Results <% 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 ( _ )

Example 1 Code (Continued) Customer Information CustomerID CompanyName ContactName Address Create a Table. Hard code the attribute names in the first row while the recordset is not empty Add the value of each attribute into HTML table using the <%= operator Move the cursor to the next available record End of the while loop

Example 2 Code (products_new.asp) New Page 1 Products with Category ID 3 <% 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. There was an error. your gonna hafta to go " & _ "ahead, and ah, try again. back okay? thanks a lot." response.end end 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., the Recordset object is empty, then send the user back to the previous page

Example 2 Code (Continued) <% howmanyfields=MyRs.fields.count for i=0 to howmanyfields-1 %> <% do while not MyRs.eof %> <% for I = 0 to howmanyfields-1 cur_field = MyRs(I).value %> <%MyRs.movenext loop%> <%MyRs.close Set MyRs= Nothing My_Conn.Close set My_Conn=nothing%> 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 variable into the table data element Move the record pointer to the next record Close the recordset and the connection and set them to nothing Output the field names for the first row

Example 3 Code (select_new.asp) Get Product from Form <% 'Establish the connection with the nowrthwind database set my_conn= Server.CreateObject("ADODB.Connection") 'Construct the connection string using relative path for the database file myvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & server.mappath("db_f03/Northwind.mdb") 'Open the connection to the data source my_conn.Open myvar 'Get the products from the products_new table StrSql= "Select * from products" set rs = my_conn.Execute (StrSql) 'Display a message if no products found if rs.BOF or rs.EOF then ' No records found response.write "Hmm... That didn't work. There was an error. " & _ "Oh well, try again. back " response.end end if %>

Example 3 Code Continued (select_new.asp) Available Products.. Please select a product and click on Submit Query to get more information. Select Product: <% do while not rs.eof %> "> <% rs.movenext 'move the cursor to the next record in the recordset loop my_Conn.Close ‘close th e connection object set my_conn = nothing %>

Example 3 Code (get_product_new.asp) Get Product from Form <% if request.form("product")="" then response.write "You must select a product in select_new.asp first." response.end end if 'Establish the connection with the nowrthwind database set my_conn= Server.CreateObject("ADODB.Connection") 'Construct the connection string using relative path for the database file myvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & server.mappath("db_f03/Northwind.mdb") 'Open the connection to the data source my_conn.Open myvar 'Construct the SQL statement by concatenating the value selected by the user StrSql= "Select * from products where productid=" & request.form("product") 'Execute the SQL statement and create a recordset set rs = my_conn.Execute (StrSql) 'Display a message if no products found if rs.BOF or rs.EOF then ' No records found response.write "Hmm... That didn't work. There was an error. Oh well, " & _ "try again. back " response.end end if %>

Example 3 Code Continued (get_product_new.asp) Information about the " " product: Product ID Product Name Supplier ID Quantity Per Unit Price Units in Stock <% do while not rs.eof %> <% rs.movenext loop 'End of do while loop my_Conn.Close ‘Close the connection object set my_conn = nothing %>

Assignment 2 Create two asp pages. The first asp page should list the Company names in a drop-down list. The user can select a Company and click on the submit button. It should call the next asp page which lists the Company information as well as the sponsorship information Database to be used: exercise2.mdb exercise2.mdb Tables to be used: Company and Projects Click to see the assignment demo Click to see the assignment demo