COS 381 Day 27. 2 Agenda  Capstone projects are DUE Wednesday, May 10 at 1PM  I will be covering ASP.NET from the handouts  There will be one lecture.

Slides:



Advertisements
Similar presentations
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
Advertisements

Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
The Web Warrior Guide to Web Design Technologies
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
Chapter 12 © 2001 by Addison Wesley Longman, Inc. 1 Chapter 12 Sebesta: Programming the World Wide Web.
COS 381 Day 23. © 2006 Pearson Addison-Wesley. All rights reserved Agenda Capstone progress report Overdue –Only received 1 out of 6 Capstone projects.
COS 381 Day 26. Agenda  Capstone projects are DUE May 10 at 1PM  I will be covering ASP.NET from the handouts  There will be one lecture on Database.
Objectives Connect to MySQL from PHP
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
Chapter 11 ASP.NET JavaScript, Third Edition. 2 Objectives Learn about client/server architecture Study server-side scripting Create ASP.NET applications.
1 Foundations of Software Design Lecture 27: Java Database Programming Marti Hearst Fall 2002.
Computer Science 101 Web Access to Databases Overview of Web Access to Databases.
2440: 141 Web Site Administration Web Server-Side Programming Professor: Enoch E. Damson.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
Web Development & Design Foundations with XHTML Chapter 9 Key Concepts.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
1 Web Developer & Design Foundations with XHTML Chapter 6 Key Concepts.
Chapter 9 Using Perl for CGI Programming. Computation is required to support sophisticated web applications Computation can be done by the server or the.
Chapter 14 Database Access through the Web. © 2006 Pearson Addison-Wesley. All rights reserved Relational Databases - A database is a collection.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
Chapter 14 © 2005 by Addison Wesley Longman, Inc Relational Databases - A database is a collection of data organized to allow relatively easy access.
Chapter 13 © 2013 by Pearson Relational Databases - A database is a collection of data organized to allow relatively easy access for retrievals,
Chapter 6: Forms JavaScript - Introductory. Previewing the Product Registration Form.
ASP.NET Programming with C# and SQL Server First Edition
© Wang Bin 2004 JDBC ----Java Database Connectivity.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Database Programming in Java Corresponds with Chapter 32, 33.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Database Access Through the Web.
Chapter 13 © 2010 by Addison Wesley Longman, Inc Relational Databases - A database is a collection of data organized to allow relatively easy access.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Announcements Read JDBC Project Step 5, due Monday.
Web Server Administration Chapter 7 Installing and Testing a Programming Environment.
1 Accelerated Web Development Course JavaScript and Client side programming Day 2 Rich Roth On The Net
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
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.
Chapter 10: The Data Tier We discuss back-end data storage for Web applications, relational data, and using the MySQL database server for back-end storage.
Web-Based Database Programming with PHP. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn PHP Basics PHP functions –To.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
Java Database Connectivity (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Chapter 13 © 2010 by Addison Wesley Longman, Inc Relational Databases - A database is a collection of data organized to allow relatively easy access.
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 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
JDBC CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
Basics of JDBC Session 14.
ASP-2-1 SERVER AND CLIENT SIDE SCRITPING Colorado Technical University IT420 Tim Peterson.
CP476 Internet Computing Perl CGI and MySql 1 Relational Databases –A database is a collection of data organized to allow relatively easy access for retrievals,
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
Chapter 13 © 2009 by Addison Wesley Longman, Inc Relational Databases - A database is a collection of data organized to allow relatively easy access.
Web Database Programming Using PHP
13.1 Relational Databases - A database is a collection of data organized to allow relatively easy access for retrievals, additions, and deletions - A relational.
Web Database Programming Using PHP
JDBC.
ISC440: Web Programming 2 Server-side Scripting PHP 3
PHP.
Web DB Programming: PHP
Presentation transcript:

COS 381 Day 27

2 Agenda  Capstone projects are DUE Wednesday, May 10 at 1PM  I will be covering ASP.NET from the handouts  There will be one lecture on Database access  Quiz 4 on May 4 ASP.NET and Database Access  Assignment 7 (final one) is posted and is Due on May 3 at Midnight Create a complex ASP.NET page ssign7/UMFKorder.aspx ssign7/UMFKorder.aspx

3 Event Handling in ASP.NET  Events are messages sent out by objects Different objects – Different messages  In ASP.NET events occur when the server detects an event Page-Level events  Occur when users visits a web page Control events  Occur when a user manipulates an ASP.NET control

4 Page Events  Web Form trigger 11 events when loaded (in order) 1. Initialization (Page_Init) 2. Load View State 3. Post Back Data Processing 4. Page Load (Page_Load) 5. Post Back Change Notification 6. Post Back Event Processing 7. Pre-rendering (Page_PreRender) 8. Same view State 9. Rendering 10. Disposing 11. Unload

5 Page Level Events  These events do not need to be registered  Most common Used Page Event is Page_Load protected void Page_Load(Object Src, EventArgs E) { if (!PostBack) DataBind(); }  Example (code) Example(code)

6 Control Events  Must have registered Handlers Use Delegates which listen for events and then delegating responsibility for the event to the assigned handler Generally event handlers (like Page_Load) have two parameters  Object src The object which created the event  EventArgs E Specific information about the event

7 Creating a handler for a ASP.NET Control  ASP.NET Control must be in a Web Form that is set to runat=‘server”  Use Dreamweaver Wizard

8 Control Events  The Dreamweaver wizard will register the event but you still need to write the handler code Between tags in Head void btnTest_OnClick( Object Src, EventsArgs E) { Some C# code } ExampleExample (Code)(Code)

9 Adding Controls and Events Programmatically  Between tags in head Button btnTest = new Button(); btnTest.Text = “daButton”; btnTest.Click += new EventHandler(this.btnTest_OnClick); samePanel.Controls.Add(“btnTest”); Make sure you write the btnTest_Onclick functions  Example (code) Example(code)

10 Complex Controls  Have lots of functionality; sometimes called rich controls  We will look at two complex controls Ad Rotator File upload  You can create your own Complex Controls

11 AD Rotator  Places Different images in your Web Form every time someone loads the page. Images are licked to a web site 3 Parts  Images  The ASP.NET Ad Rotator Control  A XML configuration file Example (Code) Example(Code)

12 XML config File  *.jpg URL text 50 Macromedia *.jpg UrL Text 30 Microsoft example

13 Adding The Ad Rotator Control  Use Dreamweaver wizard More tags icon Under ASP.NET tags use asp:adrotatoor

14 Web Form Validation  Input fields need to be checked Check for errors before using the data in a program or putting into a database We can check for  Existence  Format  Range of vales  Data type  ASP.NET includes validation controls that automatically provide form field validation with little or no extra coding

15 Preprogrammed Validators  Does both client side and server side validation of data DHTML  CSS  JavaScript  ASP.NET includes 5 preprogrammed Validators Required field Range Compare Regular expression Custom

16 Adding a Required field validator  Must use a Web Form that runat=‘server”

17 Adding a Validation summary  This is a place for all the validation errors to appear ExampleExample (code)(code)

18 Value Based Validators  Required Text Validators only require that some text is entered but you may want to check to actual text entered Compare against  Value (compare validator)  Type (compare validator)  Another control (compare validator)  A regular expression (regular expression validator)  A range of values (range validator)  Other conditions (custom validator)

19 Adding value Validators

20 Regular Expression  Same as JavaScript and Perl \w is alpha char \d is decimal char * zero or more + one or more ? Zero or one. Matches any character except newline [] range of characters [A-Z] upper case \* matches *  Matches s

21 Validations examples  Compare, Range & Regular expression Example (code) Example(code)  Custom validator Example (code) Example(code)  Assignment #7

Chapter 14 Database Access through the Web

© 2006 Pearson Addison-Wesley. All rights reserved Relational Databases - A database is a collection of data organized to allow relatively easy access for retrievals, additions, and deletions - A relational database is a collection of tables of data, each of which has one special column that stores the primary keys of the table - Rows are sometimes called entities - Designing a relational database for used Corvettes that are for sale - Could just put all data in a single table, whose key would be a simple sequence number - The table could have information about various equipment the cars could have - Better to put the equipment in a different table and use a cross-reference table to relate cars to equipment - Use a separate table for state names, with only references in the main table

© 2006 Pearson Addison-Wesley. All rights reserved Relational Databases (continued) - Logical model Corvettes States Corvettes_ Equipment Equipment - Implementation Vette_idBody_styleMiles YearState 1coupe hatchback convertible hatchback hatchback hardtop coupe Convertible hardtop hatchback Figure 13.2 The Corvettes table

© 2006 Pearson Addison-Wesley. All rights reserved Relational Databases (continued) State_idState 1Alabama 2Alaska 3Arizona 4Arkansas 5California 6Colorado 7Connecticut 8Delaware 9Florida 10Georgia Figure 13.3 The States table Equip_idEquipment 1Automatic 24-speed 35-speed 46-speed 5CD 6leather Figure 13.4 The Equipment table

© 2006 Pearson Addison-Wesley. All rights reserved Relational Databases (continued) Vette_idEquip Figure 13.5 The Corvettes-Equipment cross-reference table

© 2006 Pearson Addison-Wesley. All rights reserved Intro to SQL - A standard language to create, query, and modify databases - Supported by all major database vendors - More like structured English than a programming language - We cover only six basic commands: CREATE TABLE, SELECT, INSERT, UPDATE, DELETE, and DROP - SQL reserved words are case insensitive - The CREATE TABLE command: CREATE TABLE table_name ( column_name 1 data_type constraints, … column_name n data_type constraints ) - There are many different data types ( INTEGER, FLOAT, CHAR( length ), …)

© 2006 Pearson Addison-Wesley. All rights reserved Intro to SQL (continued) - There are several constraints possible e.g., NOT NULL, PRIMARY KEY CREATE TABLE States ( State_id INTEGER PRIMARY KEY NOT NULL, State CHAR(20)) - The SELECT Command - Used to specify queries - Three clauses: SELECT, FROM, and WHERE - General form: SELECT column names FROM table names WHERE condition SELECT Body_style FROM Corvettes WHERE Year > 1994

© 2006 Pearson Addison-Wesley. All rights reserved Intro to SQL (continued) - The INSERT Command INSERT INTO table_name ( col_name 1, … col_name n ) VALUES ( value 1, …, value n ) - The correspondence between column names and values is positional INSERT INTO Corvettes(Vette_id, Body_style, Miles, Year, State) VALUES (37, 'convertible', 25.5, 1986, 17) - The UPDATE Command - To change one or more values of a row in a table UPDATE table_name SET col_name 1 = value 1, … col_name n = value n WHERE col_name = value - The WHERE clause is the primary key of the row to be updated

© 2006 Pearson Addison-Wesley. All rights reserved Intro to SQL (continued) - Example: UPDATE Corvettes SET Year = 1996 WHERE Vette_id = 17 - The DELETE Command - Example: DELETE FROM Corvettes WHERE Vette_id = 27 - The WHERE clause could specify more than one row of the table - The DROP Command - To delete whole databases or complete tables DROP ( TABLE | DATABASE ) [ IF EXISTS ] name DROP TABLE IF EXISTS States

© 2006 Pearson Addison-Wesley. All rights reserved Intro to SQL (continued) - Joins - If you want all cars that have CD players, you need information from two tables, Corvettes and Equipment - SELECT can build a temporary table with info from two tables, from which the desired results can be gotten - this is called a join of the two tables - A SELECT that does a join operation specifies two tables in its FROM clause and also has a compound WHERE clause - For our example, we must have three WHERE conditions 1. Vette_id s from Corvettes and c orvettes_Equipment must match 2. Equip from Corvettes_Equipment must match the Equip_id from Equipment 3. The Equip from Equipment must be CD

© 2006 Pearson Addison-Wesley. All rights reserved Intro to SQL (continued) SELECT Corvettes.Vette_id, Corvettes.Body_style, Corvettes.Miles, Corvettes.Year, Corvettes.State, Equipment.Equip FROM Corvettes, Equipment WHERE Corvettes.Vette_id = Corvettes_Equipment.Vette_id AND Corvettes_Equipment.Equip = Equipment.Equip_id AND Equipment.Equip = 'CD' This query produces VETTE_ID BODY_STYLE MILES YEAR STATE EQUIP. 1 coupe CD 2 hatchback CD 8 convertible CD 9 hardtop CD 10 hatchback CD

© 2006 Pearson Addison-Wesley. All rights reserved Architectures for Database Access - Client-Server Architectures - Client tasks: - Provide a way for users to submit queries - Run applications that use the results of queries - Display results of queries - Server tasks: - Implement a data manipulation language, which can directly access and update the database - A two-tier system has clients that are connected directly to the server - Problems with a two-tier system: - Because the relative power of clients has grown considerably, we could shift processing to the client, but then keeping all clients current with application updates is difficult

© 2006 Pearson Addison-Wesley. All rights reserved Architectures for Database Access - A solution to the problems of two-tier systems is to add a component in the middle - create a three-tier system - For Web-based database access, the middle tier can run applications (client just gets results) Client Middle tier Server Browser Web Server Database & Apps System - Database Access with Embedded SQL - SQL commands are embedded in programs written in a host programming language, whose compiler is extended to accept some form of SQL commands - Advantage: - One package has computational support of the programming language, as well as database access with SQL

© 2006 Pearson Addison-Wesley. All rights reserved Architectures for Database Access (continued) - Disadvantage (of embedded SQL): - Portability among database systems - Microsoft Access Architecture - A tool to access any common database structure - Use either the Jet database engine, or go through the Open Database Connectivity (ODBC) standard - ODBC is an API for a set of objects and methods that are an interface to different databases - Database vendors provide ODBC drivers for their products – the drivers implement the ODBC objects and methods - An application can include SQL statements that work for any database for which a driver is available

© 2006 Pearson Addison-Wesley. All rights reserved Architectures for Database Access (continued) - The Perl DBI/DBD Architecture - Database Interface (DBI) provides methods & attributes for generic SQL commands - Database Driver (DBD) is an interface to a specific database system (MySQL, Oracle, etc.) - Convenient for Web access to databases, because the Perl program can be run as CGI on the Web server system - PHP & Database Access - An API for each specific database system - Also convenient for Web access to databases, because PHP is run on the Web server

© 2006 Pearson Addison-Wesley. All rights reserved Architectures for Database Access (continued) - The Java JDBC Architecture - Related to both embedded languages and to ODBC - JDBC is a standard protocol that can be implemented as a driver for any database system - JDBC allows SQL to be embedded in Java applications, applets, and servlets - JDBC has the advantage of portability over embedded SQL - A JDBC application will work with any database system for which there is a JDBC driver

© 2006 Pearson Addison-Wesley. All rights reserved The MySQL Database System - A free, efficient, widely used SQL implementation - Available from - Logging on to MySQL (starting it): mysql [ -h host] [ -u username] [database name] [ -p ] - Host is the name of the MySQL server - Default is the user’s machine - Username is that of the database - Default is the name used to log into the system - The given database name becomes the “focus” of MySQL - If you want to access an existing database, but it was not named in the mysql command, you must choose it for focus use cars; - Response is: Database changed

© 2006 Pearson Addison-Wesley. All rights reserved The MySQL Database System - If the focus has not been set and MySQL gets an SQL command, you get: ERROR 1046: No Database Selected - To create a new database, CREATE DATABASE cars; - Response: Query ok, 1 row affected (0.05 sec) - Example: CREATE TABLE Equipment (Equip_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, Equip INT UNSIGNED ); - To see the tables of a database: SHOW TABLES; - To see the description of a table (columns): DESCRIBE Corvettes;

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with Perl/MySQL - Needed: 1. DBI – a standard object-oriented module 2. A DBD for the specific database system - DBI Module - Get complete documentation from perldoc DBI - Interface is similar to Perl’s interface to external files – through a filehandle - To provide access to DBI and create a DBI object: use DBI; - Access to the object is through the reference variable, DBI - To connect to the database: $dbh = DBI->connect( "DBI: driver_name : database_name " [, username] [, password ]);

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with Perl/MySQL - Example: $dbh = DBI->connect("DBI:mysql:cars"); - Creates the db handle - Assumes the user name of the person logged in - Assumes the db does not need a password - The connect method is usually used with die - A Perl program can have connections to any number of databases - To create a query, we usually compile the SQL command first, then use it against the database - To create a compiled query, use prepare, as in: $sth = $dbh->prepare("SELECT Vette_id, Body_style, Year, States.State FROM Corvettes, States WHERE Corvettes.State = States.State_id AND States.State = 'California'"); - To execute a compiled query, use execute, as in: $sth->execute() or die "Error –query: $dbh->errstr\n";

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with Perl/MySQL - The $sth object now has the result of the query - To display the results, we would like column names, which are stored in a hash $col_names = $sth->{NAME}; - Rows of the result are available with the fetchrow_array method, which returns a reference to an array that has the next row of the result ( returns false if there are no more rows) - Note: Putting query results in an HTML document can cause trouble (>, <, “, and &) - Avoid the problem by using the CGI function, escapeHTML

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with PHP/MySQL - When values from a DB are to be put in XHTML, you must worry about XHTML special characters - To get rid of the XHTML special characters, use the PHP function, htmlspecialchars($str) - Replaces the special characters in the string with their corresponding XHTML entities - Another problem with PHP and XHTML forms is the string special characters ( ″, ", \, and NULL ), which could come from $_GET and $_POST - To fix these, magic_quotes_gpc in the PHP.ini file is set to ON by default - This backslashes these special characters $query = "SELECT * FROM Names WHERE Name = $name"; - If this wasn’t done and the value of $name is O'Shanter, it would prematurely terminate the query string - But with magic_quotes_gpc on, it will be converted to O\'Shanter - Unfortunately, this can create new problems

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with PHP/MySQL - For example, if a SELECT clause has a single-quoted part, like 'California', the single quotes will be implicitly backslashed, making the query illegal for MySQL - So, magic_quotes_gpc must be turned off, or else the extra backslashes can be removed with stripslashes - To connect PHP to a database, use mysql_pconnect, which can have three parameters: 1. host (default is localhost) 2. Username (default is the username of the PHP script) 3. Password (default is blank, which works if the database does not require a password) $db = mysql_pconnect(); - Usually checked for failure - Sever the connection to the database with mysql_close

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with PHP/MySQL - To focus MySQL, mysql_select_db("cars"); - Requesting MySQL Operations - Call mysql_query with a string parameter, which is $result = mysql_query($query); - Dealing with the result: 1. Get the number of rows in the result $num_rows = mysql_num_rows($result); 2. Get the rows with mysql_fetch_array for ($row_num = 0; $row_num < $num_rows; $row_num++) { $row = mysql_fetch_array($result); print " Result row number". ($row_num + 1). " State_id: "; print htmlspecialchars($row["State_id"]); print "State: "; etc.

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with PHP/MySQL - We have had it easy – the column titles were known - If they are not known, we must get them - The result rows are in PHP arrays, whose elements actually are double sets of elements - Each pair has the value, but one has a numeric key and one has a string key - For example, if the result has the field values (1, Alabama), the array has: ((0, 1), (State_id, 1), (1, Alabama), (State, Alabama)) - If the row is indexed with numbers, the element values are returned - The following displays all field values from $row $values = array_values($row); for ($index = 0; $index < $num_fields / 2; $index++) print "$values[2 * $index + 1] ";

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with PHP/MySQL (continued) - To display all column names: $keys = array_keys($row); for ($index = 0; $index < $num_fileds; $index++) print "$keys[2 * $index + 1] ";

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with PHP/MySQL - The form display document and the PHP processing document can be combined - After simply inserting the XHTML from the display document into the PHP document, several modifications are required: 1. Change the value of the action attribute of the form to the name of the combined document file 2. Create a hidden input element that sets its value when the document is first displayed. This provides a way for the document to determine which it is doing, displaying the form or processing the form data The PHP code to test this has the form: $stage = $_POST[ " stage " ]; if (!IsSet($stage))) { … } The then clause includes the form processing; the else clause includes the form display

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with JDBC/MySQL - Approaches to using JDBC outside the Web - JDBC is a Java API for database access - The API is defined in java.sql (part of Java distribution) - Can use a two-tier configuration - Disadvantage: Every client must have a driver for every database vendor - Can also use a three-tier configuration - The application runs on the client side, the middle machine runs JDBC, and the thirdsystem runs the database system - JDBC and MySQL - Connecting the application to the driver - The getConnection method of DriverManager, which selects the correct driver from those that are registered

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with JDBC/MySQL - The general form of a reference to a database for the connection operation is: jdbc: subprotocol_name : more_info - The “subprotocol” specifies the driver - For the JDBC-ODBC bridge, it is odbc - For the MySQL, it is mysql - The “more info” part depends on the specific database being used - For MySQL and the cars database, jdbc:mysql://localhost/cars?user=root - Two ways to register a database driver: 1. The general way is to have the system property jdbc.drivers maintain a list of registered drivers - Add one for mysql with jdbc.drivers = org.gjt.mm.mysql.Driver;

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with JDBC/MySQL 2. Manual registration, using the forName method of the Class class, passing the name of the driver Class.forName( "org.gjt.mm.mysql.Driver").NewInstance(); - The actual connection is made by creating a Connection object with the getConnection method of the DriverManager class DriverManager.getConnection( database_address, database_user_id, password ) - If the application owner owns the database, public can be used for both the user id and the password myCon = DriverManager.getConnection("jdbc:mysql://localhost/cars?user=root“); - SQL commands through JDBC - First, you need a Statement object Statement myStmt = myCon.createStatement();

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with JDBC/MySQL - SQL commands are String objects final String sql_com = "UPDATE Corvettes " + "Year = 1991 WHERE Vette_id = 7"); - Categories of SQL commands - Action - INSERT, UPDATE, DELETE, CREATE TABLE, and DROP TABLE - Query - SELECT - The action commands are executed with the executeUpdate method of Statement myStmt.executeUpdate(sql_com); - Returns the number of affected rows - A SELECT is executed by sending it as the actual parameter to the executeQuery method of Statement - The executeQuery method returns an object of class ResultSet - Get rows from ResultSet with next iterator

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with JDBC/MySQL ResultSet result; final String sql_com = "SELECT * FROM Corvettes WHERE Year <= 1990" result = myStmt.executeQuery(sql_com); while(result.next()) { // access and process the current element } - Information is extracted from the ResultSet object with an access method, for which there is one for each data type e.g., If an extracted row is 3, "convertible", 13.5, 2001, 1 String style; style = result.getString("Body_style"); or style = result.getString(2);

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with JDBC/MySQL - Output of Query : Corvettes For Sale Vette_id Body_style Miles Year State 1 coupe hatchback convertible hardtop convertible hardtop hatchback Metadata - to get table and column names from a database - Two kinds: 1. Metadata that describes the database 2. Metadata that describes a ResultSet object - A Connection method, getMetaData, creates an object of class DatabaseMetaData DatabaseMetaData dbmd = myCon.getMetaData();

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with JDBC/MySQL -The getTables method of DatabaseMetaData takes four parameters, only -one of which is necessary String tbl[] = {"TABLE"}; DatabaseMetaData dbmd = myCon.getMetaData(); result = dbmd.getTables( null, null, null, tbl); System.out.println( "The tables in the database are: \n\n"); while (result.next()) { System.out.println(result.getString(3)); } -Output from this: The tables in this database are: CORVETTES CORVETTES_EQUIPMENT EQUIPMENT STATES - Metadata about query results has a different tructure than general database metadata - ResultSetMetaData object

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with JDBC/MySQL (continued) ResultSetMetaData resultMd = result.getMetaData(); - We can get the number of columns, their names, types, and sizes from the resultMd object, using its methods - getColumnCount returns the number of columns - getColumnLable(i) returns the ith column’s name // Create an object for the metadata ResultSetMetaData resultMd = result.getMetaData(); // Loop to fetch and display the column names for (int i = 1; i <= resultMd.getColumnCount(); i++) { String columnName = resultMd.getColumnLabel(i); System.out.print(columnName + "\t"); } System.out.println("\n"); Output: Vette_id Body_style Miles Year State

© 2006 Pearson Addison-Wesley. All rights reserved Database Access with JDBC/MySQL (continued) - JDBC and Servlets - Use Servlet’s init to connect to the db and create the Statement object - Use doPost for the rest