Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr...

40
Programming for WWW Programming for WWW (ICE 1338) (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko .AT. i cu . ac.kr Information and Communications University (ICU)

Transcript of Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr...

Page 1: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

Programming for WWWProgramming for WWW(ICE 1338)(ICE 1338)

Lecture #11Lecture #11 July 30, 2004

In-Young Koiko .AT. icu.ac.kr

Information and Communications University (ICU)

Page 2: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 2 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

AnnouncementsAnnouncements

Your Your midterm scoremidterm score can be checked from can be checked from the class homepagethe class homepage Average: 81.0Average: 81.0

Homework #3Homework #3 is due by August 4 is due by August 4thth

Page 3: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 3 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Review of the Previous LectureReview of the Previous Lecture

XML-Based LanguagesXML-Based Languages SVG (Scalable Vector Graphics)SVG (Scalable Vector Graphics) Web ServersWeb Servers Servlets (JSP)Servlets (JSP)

Page 4: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 4 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Contents of Today’s LectureContents of Today’s Lecture

XML Addressing and LinkingXML Addressing and Linking Database Access on the WebDatabase Access on the Web

Relational DatabaseRelational Database SQLSQL Database Access ArchitecturesDatabase Access Architectures MySQLMySQL Perl/MySQLPerl/MySQL PHP/MySQLPHP/MySQL JDBC/MySQLJDBC/MySQL

Page 5: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 5 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

XLink (XML Linking Language)XLink (XML Linking Language) A generalization of the HTML link conceptA generalization of the HTML link concept Simple LinksSimple Links

<students xlink:href="students.xml"><students xlink:href="students.xml">The list of students.</students>The list of students.</students>

Extended LinksExtended Links<element xmlns:xlink="http://www.w3.org/1999/xlink/namespace/"<element xmlns:xlink="http://www.w3.org/1999/xlink/namespace/" xlink:type="extended">xlink:type="extended"> <locator href="Source" role="f"/> <locator href="Source" role="f"/> <locator href="Target" role="t"/><locator href="Target" role="t"/>

......</element></element>

External Link SetsExternal Link Sets<annot xmlns:xlink="http://www.w3.org/1999/xlink/namespace/"<annot xmlns:xlink="http://www.w3.org/1999/xlink/namespace/" role="xlink:external-linkset">role="xlink:external-linkset"> <title>DV's Annotations</title><title>DV's Annotations</title> <locator href="http://rpmfind.net/veillard/linkset.xml"/><locator href="http://rpmfind.net/veillard/linkset.xml"/></annot></annot>

http://daniel.veillard.com/Talks/2000-Linking/slide12-0.html

http://www.w3.org/XML/Linking

Page 6: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 6 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

XPathXPath A language to A language to address parts of an XML documentaddress parts of an XML document

http://www.w3.org/TR/xpath

<?xml version="1.0"?><catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd>…</catalog>

Selecting elements in an absolute path• /catalog• /catalog/cd/price• /catalog/cd[price>10.80]

Selecting elements in different levels• //cd

Selecting elements by matching patterns• /catalog/cd/*• /catalog/*/price • /*/*/price

Selecting branches• /catalog/cd[1]• /catalog/cd[last()]

Selecting attributes• //cd[@country='UK']

http://www.w3schools.com/xpath/xpath_examples.asp

Page 7: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 7 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

XPointerXPointer

Defines the fragment identifier syntax for XML Defines the fragment identifier syntax for XML resources resources

Is based on XPath (extension of XPath)Is based on XPath (extension of XPath) Returns a set of nodes, points or ranges within the Returns a set of nodes, points or ranges within the

documentdocument

ee.g., .g., #xpointer(id("foo")) #xpointer(id("foo")) xpointer(/chapter[3]/elem[@name="foo"])xpointer(/chapter[3]/elem[@name="foo"])

http://daniel.veillard.com/Talks/2000-Linking/slide12-0.html

http://www.w3.org/XML/Linking

Page 8: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 8 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Relational DatabasesRelational Databases

A database is A database is a collection of dataa collection of data organized to organized to allowallow relatively easy access for retrievals, relatively easy access for retrievals, additions, and deletionsadditions, and deletions

A relational database is A relational database is a collection of tables of a collection of tables of datadata, each of which has one special column that, each of which has one special column that stores the stores the primary keysprimary keys of the table of the table Rows are sometimes called entitiesRows are sometimes called entities

AW lecture noteshttp://coronet.iicm.edu/Dbase1/reldb_p.htm

Page 9: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 9 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Relational DB ExampleRelational DB Example

Designing a relational database for used Designing a relational database for used Corvettes that are for saleCorvettes that are for sale The table could have information about various The table could have information about various

equipment the cars could haveequipment the cars could have Use a separate table for state names, with only Use a separate table for state names, with only

references in the main tablereferences in the main table Logical Model:Logical Model:

AW lecture notes

Page 10: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 10 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Relational DB Example Relational DB Example (cont.)(cont.)

The The CorvettesCorvettes table table The The StatesStates table table

The The EquipmentEquipment table table

The The Corvettes-Corvettes-EquipmentEquipment ccross-ross-

reference tablereference table

Page 11: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 11 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

SQL (Structured Query Language)SQL (Structured Query Language)

A standard language to create, query, and A standard language to create, query, and modify databasesmodify databases

Supported by all major database vendorsSupported by all major database vendors More like structured English than a More like structured English than a

programming languageprogramming language We cover only six basic commands: We cover only six basic commands:

CREATECREATE TABLE, SELECT, INSERT, TABLE, SELECT, INSERT, UPDATE, DELETE, and DROPUPDATE, DELETE, and DROP

SQL reserved words are case insensitiveSQL reserved words are case insensitiveAW lecture notes

Page 12: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 12 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Table CreationTable Creation

The CREATE TABLE command:The CREATE TABLE command:CREATE TABLE table_name (CREATE TABLE table_name ( column_name1 data_type constraints,column_name1 data_type constraints,

…… column_namen data_type constraints)column_namen data_type constraints)

There are many different data typesThere are many different data types (INTEGER, FLOAT, (INTEGER, FLOAT, CHAR(length), …)CHAR(length), …)

There are several constraints possibleThere are several constraints possible, , e.g., NOT NULL, e.g., NOT NULL, PRIMARY KEYPRIMARY KEY

e.g.,e.g., CREATE TABLECREATE TABLE States ( States ( State_id State_id INTEGER PRIMARY KEY NOT NULLINTEGER PRIMARY KEY NOT NULL,, State State CHARCHAR(20))(20))

AW lecture notes

Page 13: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 13 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

SELECT & INSERTSELECT & INSERT

The SELECT CommandThe SELECT Command – – UsedUsed to specify queriesto specify queriese.g., e.g., SELECTSELECT Body_style Body_style FROMFROM Corvettes Corvettes WHEREWHERE Year > 1994 Year > 1994

The INSERT CommandThe INSERT Command::INSERT INTO table_name (col_name1, … col_namen)INSERT INTO table_name (col_name1, … col_namen)VALUES (value1, …, valuen)VALUES (value1, …, valuen)

The correspondence between column names andThe correspondence between column names and values is positionalvalues is positional

e.g.,e.g., INSERT INTOINSERT INTO Corvettes(Vette_id, Body_style, Corvettes(Vette_id, Body_style, Miles, Year, State)Miles, Year, State)VALUESVALUES (37, 'convertible', 25.5, 1986, (37, 'convertible', 25.5, 1986,

17)17) AW lecture notes

Page 14: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 14 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

UPDATE & DELETEUPDATE & DELETE

The UPDATE CommandThe UPDATE Command – – To To change one or change one or more values of a row in a tablemore values of a row in a table

UPDATE table_nameUPDATE table_nameSET col_name1 = value1,SET col_name1 = value1,…, …, col_namen = valuencol_namen = valuenWHERE col_name = valueWHERE col_name = value

The WHERE clause is the primary key of the row to be The WHERE clause is the primary key of the row to be updatedupdatede.g., e.g., UPDATEUPDATE Corvettes Corvettes SETSET Year = 1996 Year = 1996

WHEREWHERE Vette_id = 17 Vette_id = 17

The DELETE CommandThe DELETE Command e.g., e.g., DELETE FROMDELETE FROM Corvettes Corvettes WHEREWHERE Vette_id = 27 Vette_id = 27 The WHERE clause could specify more than one row of The WHERE clause could specify more than one row of

the tablethe table AW lecture notes

Page 15: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 15 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Delete Tables and DatabasesDelete Tables and Databases

The DROP CommandThe DROP Command – – To To delete whose delete whose databases or complete tablesdatabases or complete tables DROP (TABLE | DATABASE) [IF EXISTS] nameDROP (TABLE | DATABASE) [IF EXISTS] name e.g., e.g., DROP TABLE IF EXISTSDROP TABLE IF EXISTS States States

AW lecture notes

Page 16: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 16 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

JoinsJoins A Join is an operation to build a temporary table by A Join is an operation to build a temporary table by

combining columns from different tablescombining columns from different tables e.g., Retrieve all cars that have CD playerse.g., Retrieve all cars that have CD players

SELECTSELECT Corvettes.Vette_id, Corvettes.Body_style, Corvettes.Vette_id, Corvettes.Body_style, Corvettes.Miles, Corvettes.Year, Corvettes.Miles, Corvettes.Year,

Corvettes.StateCorvettes.State FROMFROM Corvettes, Equipment Corvettes, Equipment WHEREWHERE Corvettes.Vette_id = Corvettes_Equipment.Vette_id Corvettes.Vette_id = Corvettes_Equipment.Vette_id ANDAND Corvettes_Equipment.Equip = Equipment.Equip_id Corvettes_Equipment.Equip = Equipment.Equip_id ANDAND Equipment.Equip = 'CD' Equipment.Equip = 'CD'

AW lecture notes

Page 17: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 17 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Architectures for Database AccessArchitectures for Database Access

Client-Server (two-tier) ArchitecturesClient-Server (two-tier) Architectures Client tasks: Client tasks:

Provide a way for Provide a way for users to submit queriesusers to submit queries Run applicationsRun applications that use the results of queries that use the results of queries Display resultsDisplay results of queries of queries

Server tasks:Server tasks: Implement a data manipulation language, which Implement a data manipulation language, which

can directly can directly access and update the databaseaccess and update the database Because the relative power of clients has Because the relative power of clients has

grown considerably, we grown considerably, we could shift could shift processing to the clientprocessing to the client, but then , but then maintaining data integrity is difficultmaintaining data integrity is difficult

ClientClient

DB DB ServeServe

rr

AW lecture notes

Page 18: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 18 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Architectures for Database AccessArchitectures for Database Access

A Three-tier SystemA Three-tier System For Web-based database access, For Web-based database access, the middle the middle

tier can run applicationstier can run applications The middle tier provides The middle tier provides Web-based accessWeb-based access to to

a databasea database Client just gets resultsClient just gets results

ClientClient DB DB ServeServe

rr

Middle TierMiddle Tier

e.g., Web Browsere.g., Web Browser e.g., Web Server &e.g., Web Server &

Server ApplicationsServer Applications

(Cont.)(Cont.)

AW lecture notes

Page 19: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 19 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Embedded SQLEmbedded SQL SQL commands are embedded in programsSQL commands are embedded in programs

written in a host programming language, whose written in a host programming language, whose compiler is extended to accept some form of SQL compiler is extended to accept some form of SQL commandscommands e.g., e.g., int a;int a;

EXEC SQL SELECT gpa INTO :aEXEC SQL SELECT gpa INTO :aFROM Student WHERE SID=2001234;FROM Student WHERE SID=2001234;printf("The GPA is %d\n", a);printf("The GPA is %d\n", a);

Advantage: One package has computational support of Advantage: One package has computational support of the programming language, as well as database access the programming language, as well as database access with SQLwith SQL

Disadvantage:Portability among database systemsDisadvantage:Portability among database systemsAW lecture notes

Page 20: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 20 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Database Access MechanismsDatabase Access Mechanisms

Microsoft Access ArchitectureMicrosoft Access Architecture A tool to access any common database structureA tool to access any common database structure Provides an API for a set of objects and methods that Provides an API for a set of objects and methods that

are an interface to different databasesare an interface to different databases The Perl DBI/DBD ArchitectureThe Perl DBI/DBD Architecture

Database Interface (DBI)Database Interface (DBI) provides methods & attributes provides methods & attributes for generic SQL commandsfor generic SQL commands

Database Driver (DBD)Database Driver (DBD) is an interface to a specific is an interface to a specific database system (MySQL, Oracle, etc.)database system (MySQL, Oracle, etc.)

Convenient for Convenient for Web access to databasesWeb access to databases, because the , because the Perl program can be run as CGI on the Web server Perl program can be run as CGI on the Web server systemsystem AW lecture notes

Page 21: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 21 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Database Access MechanismsDatabase Access Mechanisms PHP & Database AccessPHP & Database Access

An API for each specific database systemAn API for each specific database system Also convenient for Also convenient for Web access to databasesWeb access to databases, because , because

PHP is run on the Web serverPHP is run on the Web server The Java JDBC ArchitectureThe Java JDBC Architecture

JDBC is a standard protocol that can be implemented JDBC is a standard protocol that can be implemented as a driver for any database systemas a driver for any database system

JDBC allows SQL to be embedded in Java applications, JDBC allows SQL to be embedded in Java applications, applets, and servletsapplets, and servlets

JDBC has the JDBC has the advantage of portabilityadvantage of portability over embedded over embedded SQLSQL

A JDBC application will work with any database system A JDBC application will work with any database system for which there is a JDBC driverfor which there is a JDBC driver

AW lecture notes

Page 22: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 22 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

The MySQL Database SystemThe MySQL Database System

A free, efficient, widely used SQL implementationA free, efficient, widely used SQL implementation Available from Available from http://www.mysql.orghttp://www.mysql.org Logging on to MySQL (starting it):Logging on to MySQL (starting it):

mysqlmysql [-h host] [-u username] [database name] [-p] [-h host] [-u username] [database name] [-p] The given database name becomes the The given database name becomes the focusfocus of of

MySQLMySQL Database focus can be changed by the Database focus can be changed by the useuse

command:command: e.g., e.g., useuse cars; cars;

AW lecture notes

Page 23: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 23 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

MySQL CommandsMySQL Commands

To create a new databaseTo create a new databasee.g., e.g., CREATE DATABASECREATE DATABASE cars; cars;

To create a database tableTo create a database tablee.g., e.g., CREATE TABLECREATE TABLE Equipment Equipment

(Equip_id (Equip_id INT UNSIGNED NOT NULL INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEYAUTO_INCREMENT PRIMARY KEY,, Equip Equip INT UNSIGNEDINT UNSIGNED););

To see the tables of a database:To see the tables of a database:SHOW TABLES;SHOW TABLES;

To see the description of a table (columns):To see the description of a table (columns):e.g., e.g., DESCRIBEDESCRIBE Corvettes; Corvettes;

AW lecture notes

Page 24: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 24 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Database Access with Perl/MySQLDatabase Access with Perl/MySQL

Needed:Needed: DBIDBI – a standard object-oriented module – a standard object-oriented module DBDDBD –– for the specific database system for the specific database system

DBI ModuleDBI Module Interface is similar to Perl’s interface to external Interface is similar to Perl’s interface to external

files – through a filehandlefiles – through a filehandle To provide access to DBI and create a DBI To provide access to DBI and create a DBI

object: object: use DBI;use DBI; Access to the objectAccess to the object is through the is through the

reference variable, DBIreference variable, DBI AW lecture notes

Page 25: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 25 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Perl/MySQL Perl/MySQL (cont.)(cont.)

To connect to the database:To connect to the database: $dbh = DBI->connect( $dbh = DBI->connect(

"DBI:"DBI:driver_namedriver_name::db_namedb_name [, username] [, password]);[, username] [, password]);

e.g., e.g., $dbh = $dbh = DBI->connectDBI->connect("DBI:mysql:cars");("DBI:mysql:cars"); The The connectconnect method is usually used with method is usually used with diedie

ee.g., .g., $dbh = $dbh = DBI->connectDBI->connect("DBI:mysql:cars")("DBI:mysql:cars") oror diedie("Could not connect!");("Could not connect!");

A Perl program can have A Perl program can have connections to any connections to any number of databasesnumber of databases

AW lecture notes

Page 26: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 26 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Perl/MySQL Perl/MySQL (cont.)(cont.)

To create a query, we usually To create a query, we usually compilecompile the SQL the SQL commandcommand first, then use it against the database first, then use it against the databasee.g., e.g., $sth = $dbh->$sth = $dbh->prepareprepare((

"SELECT Vette_id, Body_style, Year, States.State"SELECT Vette_id, Body_style, Year, States.State

FROM Corvettes, StatesFROM Corvettes, States

WHERE Corvettes.State = States.State_id WHERE Corvettes.State = States.State_id

AND States.State = 'California'");AND States.State = 'California'"); To execute a compiled query, use execute, as in:To execute a compiled query, use execute, as in:

e.g., e.g., $sth->$sth->executeexecute() or() or

die "Error –query: $dbh->die "Error –query: $dbh->errstrerrstr\n";\n";

AW lecture notes

Page 27: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 27 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Perl/MySQL ExamplePerl/MySQL Example

#!/usr/bin/perl -w#!/usr/bin/perl -wuse DBI;use DBI;use CGI ":standard";use CGI ":standard";print header();print header();print start_html("CGI-Perl MySQL database access");print start_html("CGI-Perl MySQL database access");my $dbh = my $dbh = DBI->connectDBI->connect("DBI:mysql:cars", "root", "");("DBI:mysql:cars", "root", "");my $query = param("query");my $query = param("query");print "<p> <b> The query is: </b>", $query, "</p>";print "<p> <b> The query is: </b>", $query, "</p>";my $sth = $dbh->my $sth = $dbh->prepareprepare($query);($query);$sth->$sth->executeexecute or or diedie "Error - unable to execute query: $dbh-> "Error - unable to execute query: $dbh->errstrerrstr\n";\n";

access_cars.placcess_cars.pl

Page 28: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 28 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Perl/MySQL Perl/MySQL (cont.)(cont.)

The The $sth$sth object keeps the result of a query object keeps the result of a query To display the results, we would like To display the results, we would like column column

namesnames, which are stored in a hash, which are stored in a hash $col_names = $sth->{NAME};$col_names = $sth->{NAME};

Rows of the result are available with the Rows of the result are available with the fetchrow_arrayfetchrow_array method, which returns a method, which returns a reference to an array that has the next row reference to an array that has the next row of the resultof the result Returns false if there are no more rowsReturns false if there are no more rows

AW lecture notes

Page 29: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 29 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Perl/MySQL Perl/MySQL (cont.)(cont.)

Putting query results in an HTML document Putting query results in an HTML document can cause trouble (>, <, “, and &)can cause trouble (>, <, “, and &) Avoid the problem by using the CGI function, Avoid the problem by using the CGI function,

escapeHTMLescapeHTML

AW lecture notes

Page 30: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 30 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Perl/MySQL ExamplePerl/MySQL Exampleprint print "<table> <caption> <h2> Query Results </h2> </caption>", "<tr align = 'center'>";"<table> <caption> <h2> Query Results </h2> </caption>", "<tr align = 'center'>";my $col_names = my $col_names = $sth->{NAME}$sth->{NAME};;foreach $field_name (@$col_names) {foreach $field_name (@$col_names) { print "<th> $field_name </th>";print "<th> $field_name </th>";}}print "</tr>";print "</tr>";while (@result_rows = while (@result_rows = $sth->fetchrow_array$sth->fetchrow_array) {) { print "<tr align = 'center'>";print "<tr align = 'center'>"; while ($#result_rows >= 0) {while ($#result_rows >= 0) { $field = shift @result_rows;$field = shift @result_rows; $field = $field = escapeHTMLescapeHTML($field);($field); print "<td> $field </td>";print "<td> $field </td>"; }} print "</tr>";print "</tr>";}}print "</table>";print "</table>";$sth->finish;$sth->finish;$dbh->$dbh->disconnect;disconnect;print end_html();print end_html();

access_cars.placcess_cars.pl

Page 31: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 31 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

PHP/MySQL ExamplePHP/MySQL Example<html><html><head><title> Access the cars database with MySQL </title></head><head><title> Access the cars database with MySQL </title></head><body><body><?php<?php$db = $db = mysql_connectmysql_connect("localhost", "root", ""); // Connect to MySQL("localhost", "root", ""); // Connect to MySQLif (!$db) {if (!$db) { print "Error - Could not connect to MySQL"; exit;print "Error - Could not connect to MySQL"; exit;}}$er = $er = mysql_select_dbmysql_select_db("cars"); // Select the cars database("cars"); // Select the cars databaseif (!$er) {if (!$er) { print "Error - Could not select the cars database"; exit;print "Error - Could not select the cars database"; exit;}}trim(trim($query$query););print "<p> <b> The query is: </b> " . $query . "</p>";print "<p> <b> The query is: </b> " . $query . "</p>";$result = $result = mysql_querymysql_query(($query$query); // Execute the query); // Execute the queryif (!$result) {if (!$result) { print "Error - the query could not be executed";print "Error - the query could not be executed"; $error = mysql_error();$error = mysql_error(); print "<p>" . $error . "</p>";print "<p>" . $error . "</p>"; exit;exit;}}

access_cars.phpaccess_cars.php

Page 32: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 32 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

PHP/MySQL ExamplePHP/MySQL Exampleprint "<table><caption> <h2> Query Results </h2> </caption>";print "<table><caption> <h2> Query Results </h2> </caption>";print "<tr align = 'center'>";print "<tr align = 'center'>";$num_rows = $num_rows = mysql_num_rowsmysql_num_rows($result);($result);$row = $row = mysql_fetch_arraymysql_fetch_array($result);($result);$num_fields = sizeof($row);$num_fields = sizeof($row);while ($next_element = each($row)) { // Produce the column labelswhile ($next_element = each($row)) { // Produce the column labels $next_element = each($row);$next_element = each($row); $next_key = $next_element['key'];$next_key = $next_element['key']; print "<th>" . $next_key . "</th>";print "<th>" . $next_key . "</th>";}}print "</tr>";print "</tr>";for ($row_num = 0; $row_num < $num_rows; $row_num++) {for ($row_num = 0; $row_num < $num_rows; $row_num++) { reset($row); reset($row); print "<tr align = 'center'>";print "<tr align = 'center'>"; for ($field_num = 0; $field_num < $num_fields / 2; $field_num++)for ($field_num = 0; $field_num < $num_fields / 2; $field_num++) print "<th>" . $row[$field_num] . "</th> ";print "<th>" . $row[$field_num] . "</th> "; print "</tr>";print "</tr>"; $row = $row = mysql_fetch_arraymysql_fetch_array($result);($result);}}print "</table>";print "</table>";?>?></body></html></body></html>

access_cars.phpaccess_cars.php

Page 33: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 33 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Database Access with JDBC/MySQLDatabase Access with JDBC/MySQL

Approaches to using JDBC outside the WebApproaches to using JDBC outside the Web JDBC is a JDBC is a Java API for database accessJava API for database access The API is defined in the The API is defined in the java.sqljava.sql package package Can use a Can use a two-tier configurationtwo-tier configuration

Disadvantage: Every client must have a driver Disadvantage: Every client must have a driver for every database vendorfor every database vendor

Can also use a Can also use a three-tier configurationthree-tier configuration The application runs on the client side, the The application runs on the client side, the

middle machine runs JDBC, and the third middle machine runs JDBC, and the third system runs the database systemsystem runs the database system

AW lecture notes

Page 34: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 34 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

JDBC/MySQLJDBC/MySQL Connecting the application to the driverConnecting the application to the driver

The The getConnectiongetConnection method of method of DriverManagerDriverManager, which , which select the correct driver from those that are registeredselect the correct driver from those that are registered

The general form of a reference to a database for the The general form of a reference to a database for the connection operation is:connection operation is:

jdbc:subprotocol_name:more_infojdbc:subprotocol_name:more_info The “subprotocol” specifies the driver (e.g., odbc, mysql)The “subprotocol” specifies the driver (e.g., odbc, mysql) The “more info” part depends on the specific database being usedThe “more info” part depends on the specific database being used

ee.g., For MySQL and the cars database,.g., For MySQL and the cars database,

myCon = myCon = DriverManager.getConnectionDriverManager.getConnection(( ""jdbc:mysql://localhost/cars?user=rootjdbc:mysql://localhost/cars?user=root");");

AW lecture notes

Page 35: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 35 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

JDBC/MySQLJDBC/MySQL

SQL commands through JDBCSQL commands through JDBCStatement myStmt = myCon.Statement myStmt = myCon.createStatementcreateStatement();();

SQL commands are String objectsSQL commands are String objectse.g., e.g., final String sql_com = "UPDATE Corvettes " + final String sql_com = "UPDATE Corvettes " + "Year = 1991 WHERE Vette_id = 7";"Year = 1991 WHERE Vette_id = 7";

The action commands are executed with the The action commands are executed with the executeUpdate method of StatementexecuteUpdate method of Statement

e.g., e.g., myStmt.myStmt.executeUpdateexecuteUpdate(sql_com);(sql_com);

Returns the number of affected rowsReturns the number of affected rowsAW lecture notes

Page 36: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 36 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

JDBC/MySQLJDBC/MySQL A SELECT is executed by sending it as the actual A SELECT is executed by sending it as the actual

parameter to the parameter to the executeQueryexecuteQuery method of method of StatementStatement The executeQuery method returns an object of class The executeQuery method returns an object of class

ResultSetResultSet Get rows from ResultSet with Get rows from ResultSet with nextnext iterator iteratore.g.,e.g., ResultSet result;ResultSet result; final String sql_com = "SELECT * FROM final String sql_com = "SELECT * FROM

Corvettes Corvettes WHERE Year <= 1990"WHERE Year <= 1990"

result = myStmt.result = myStmt.executeQueryexecuteQuery(sql_com); (sql_com); while(result.while(result.nextnext()) {()) {

String aCol = result.String aCol = result.getStringgetString(2)(2);;String style = result.String style = result.getStringgetString("Body_style")("Body_style");;

}} AW lecture notes

Page 37: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 37 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

JDBC/MySQL MetadataJDBC/MySQL Metadata

Metadata - to get table and column names Metadata - to get table and column names from a database from a database

Two kinds of metadata:Two kinds of metadata: Metadata that describes the databaseMetadata that describes the database

DatabaseMetaData DatabaseMetaData dbmd = myCon.dbmd = myCon.getMetaDatagetMetaData();(); Metadata that describes a ResultSet objectMetadata that describes a ResultSet object

ResultSetMetaData ResultSetMetaData resultMd = result.resultMd = result.getMetaDatagetMetaData();();

AW lecture notes

Page 38: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 38 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

JDBC/MySQL Database MetadataJDBC/MySQL Database Metadata

String tbl[] = { "TABLE" };String tbl[] = { "TABLE" };DatabaseMetaData dbmd = myCon.DatabaseMetaData dbmd = myCon.getMetaDatagetMetaData();();result = dbmd.result = dbmd.getTablesgetTables(null, null, null, tbl);(null, null, null, tbl);System.out.println("The tables in the database are: \n\n");System.out.println("The tables in the database are: \n\n");while (result.next()) {while (result.next()) { System.out.println(result.System.out.println(result.getStringgetString(3));(3));}}

Output from this:Output from this: The tables in this database are:The tables in this database are: CORVETTESCORVETTES CORVETTES_EQUIPMENTCORVETTES_EQUIPMENT EQUIPMENTEQUIPMENT STATESSTATES AW lecture notes

Page 39: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 39 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

JDBC/MySQL Result MetadataJDBC/MySQL Result Metadata

// Create an object for the metadata// Create an object for the metadataResultSetMetaData resultMd = result.ResultSetMetaData resultMd = result.getMetaDatagetMetaData();();// Loop to fetch and display the column names// Loop to fetch and display the column namesfor (int i = 1; i" <= resultMd.for (int i = 1; i" <= resultMd.getColumnCountgetColumnCount(); i++) {(); i++) { String columnName = resultMd.String columnName = resultMd.getColumnLabelgetColumnLabel(i);(i); System.out.print(columnName + "\t");System.out.print(columnName + "\t");}}System.out.println("\n");System.out.println("\n");

Output:Output:Vette_id Body_style Miles Year StateVette_id Body_style Miles Year State

AW lecture notes

Page 40: Programming for WWW (ICE 1338) Lecture #11 Lecture #11 July 30, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT.

July 30, 2004 40 Programming for WWW (Lecture#11) In-Young Ko, Information Communications University

Web-based DB ReferencesWeb-based DB References

Introduction to Relational Database DesignIntroduction to Relational Database Design: : http://www.edm2.com/0612/msql7.htmlhttp://www.edm2.com/0612/msql7.html

XML representation of a relational XML representation of a relational databasedatabase: : http://www.w3.org/XML/RDB.htmlhttp://www.w3.org/XML/RDB.html