Think Possibility Integrating Web Applications With Databases.

31
hink Possibility Integrating Web Applications Integrating Web Applications With Databases With Databases

Transcript of Think Possibility Integrating Web Applications With Databases.

Page 1: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Integrating Web Integrating Web Applications With DatabasesApplications With Databases

Page 2: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Database Overview

• A database is a collection of logically related data. It is usually managed bya a database management system (DBMS).

• For an RDBMS, the language standard that supports database operations is called Structured Query Language (SQL).

Page 3: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Database Overview

• An RDBMS allows you to perform four fundamental operations:

1. Create a row in a table.2. Retrieve one or more rows in a table.3. Update some data in a table4. Delete one or more rows in a table.

Page 4: Think Possibility Integrating Web Applications With Databases.

Think Possibility

The JDBC API

• JDBC is the Java technology API for interacting with a DBMS.

• The JDBC API includes interfaces that manage connections to the DBMS, statements to perform operations and result sets that encapsulate the result of retrieval operations.

Page 5: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Introduction to JDBC

• JDBC is a simple API for connecting from Java applications to multiple databases.

• Lets you smoothly translate between the world of the database, and the world of the Java application.

• The idea of a universal database access API is not a new one. For example, Open Database Connectivity (ODBC) was developed to create a single standard for database access in the Windows environment.

• JDBC API aims to be as simple as possible while providing developers with maximum flexibility.

Page 6: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Understanding JDBC Drivers

• To connect to a database, you first need a JDBC Driver.

• JDBC Driver: set of classes that interface with a specific database

engine.

Java Application

JDBC Driver Manager

JDBC-ODBC Bridge

VendorSpecific

JDBC Driver

VendorSpecific

JDBC Driver

Database

Database

Diagram Source: Marty Hall,Core Web Programming(Prentice Hall.)

Page 7: Think Possibility Integrating Web Applications With Databases.

Think Possibility

JDBC Drivers

• JDBC drivers exist for every major database including: Oracle, SQL Server, Sybase, and MySQL.

• For MySQL, we will be using the open source MySQL Connector/J.

• http://www.mysql.com/downloads/api-jdbc.html.

Page 8: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Installing the MySQL Driver

• To use the MySQL Connector/J Driver, you need to download the complete distribution.

• Once you have extracted the distribution archive, you can install the driver by placing mysql-connector-java-[version]-bin.jar in your classpath, either by adding the FULL path to it to your CLASSPATH enviornment variable.

• To use the driver within Tomcat, copy the jar file above to: [TOMCAT_HOME]\webapps\ROOT\WEB-INF\

lib

Page 9: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Six Steps to Using JDBC

1. Load the JDBC Driver2. Establish the Database Connection3. Create a Statement Object4. Execute a Query5. Process the Results6. Close the Connection

Page 10: Think Possibility Integrating Web Applications With Databases.

Think Possibility

1) Loading the JDBC Driver

• To use a JDBC driver, you must load the driver via the Class.forName() method.

• In general, the code looks like this:Class.forName("jdbc.DriverXYZ");– where jbdc.DriverXYZ is the JDBC Driver you

want to load.

• If you are using a JDBC-ODBC Driver, your code will look like this:Class.forName("sun.jdbc.odbc.JdbcOdbcDri

ver");

Page 11: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Loading the MySQL Driver

• With MySQL Connector/J, the name of this class is com.mysql.jdbc.Driver. With this method, you could use an external configuration file to supply the driver class name and driver parameters to use when connecting to a database.try{Class.forName("com.mysql.jdbc.Driver");

} catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException:

"); System.err.println(e.getMessage());}• Class.forName() will throw a ClassNotFoundException if

your CLASSPATH is not set up properly.• Hence, it's a good idea to surround the forName() with

a try/catch block.

Page 12: Think Possibility Integrating Web Applications With Databases.

Think Possibility

2) Establish the Connection

• Once you have loaded your JDBC driver, the next step is to establish a database connection.

• The following line of code illustrates the basic idea:

Connection con = DriverManager.getConnection(url,"myLogin", "myPassword");

Page 13: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Creating a Connection URL

• The only difficulty in establishing a connection is specifying the correct URL.

• In general, the URL has the following format: jdbc:subprotocol:subname.– JDBC indicates that this is a JDBC Connection

(no mystery there! )– The subprotocol identifies the driver you want

to use.– The subname identifies the database

name/location.

Page 14: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Example - ODBC

• If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: .

• The rest of the URL is generally your data source name or database system.

String url = "jdbc:odbc:basketball"; Connection con = DriverManager.getConnection(url, “admin", “adminpasswd");

Page 15: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Example - MySQL

• Here's how you might connect to MySQL:

String url = "jdbc:mysql://localhost/basketball";Connection con =

DriverManager.getConnection(url);

• In this case, we are using the MySQL JDBC Driver to connect to the basketball database, located on the localhost machine.

• If this code executes successfully, we will have a Connection object for communicating directly with the database.

Page 16: Think Possibility Integrating Web Applications With Databases.

Think Possibility

3) Create a Statement Object

• The JDBC Statement object sends SQL statements to the database.

• Statement objects are created from active Connection objects.

• For example:Statement stmt = con.createStatement();

• With a Statement object, you can issue SQL calls directly to the database.

Page 17: Think Possibility Integrating Web Applications With Databases.

Think Possibility

4) Execute a Query

• executeQuery()– Executes the SQL query and returns the data in a

table (ResultSet)– The resulting table may be empty but never null

ResultSet results =stmt.executeQuery("SELECT a, b FROM table");

• executeUpdate()– Used to execute for INSERT, UPDATE, or DELETE

SQL statements – The return is the number of rows that were

affected in the database– Supports Data Definition Language (DDL)

statements CREATE TABLE, DROP TABLE and ALTER TABLE

Page 18: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Useful Statement Methods

• getMaxRows/setMaxRows– Determines the number of rows a ResultSet

may contain

– Unless explicitly set, the number of rows are unlimited (return value of 0)

• getQueryTimeout/setQueryTimeout– Specifies the amount of a time a driver will

wait for a STATEMENT to complete before throwing a SQLException

Page 19: Think Possibility Integrating Web Applications With Databases.

Think Possibility

5) Process the Results

• A ResultSet contains the results of the SQL query.

• Useful Methods

• All methods can throw a SQLException

– close• Releases the JDBC and database resources• The result set is automatically closed when the

associated Statement object executes a new query

– getMetaDataObject• Returns a ResultSetMetaData object containing

information about the columns in the ResultSet

Page 20: Think Possibility Integrating Web Applications With Databases.

Think Possibility

ResultSet (Continued)

• Useful Methods

– next• Attempts to move to the next row in the

ResultSet– If successful true is returned; otherwise,

false– The first call to next positions the cursor

a the first row

Page 21: Think Possibility Integrating Web Applications With Databases.

Think Possibility

ResultSet (Continued)

• Useful Methods– findColumn

• Returns the corresponding integer value corresponding to the specified column name

• Column numbers in the result set do not necessarily map to the same column numbers in the database

– getXxx• Returns the value from the column specified

by column name or column index as an Xxx Java type

• Returns 0 or null, if the value is a SQL NULL• Legal getXxx types: double byte

intDate String

floatshort long

Time Object

Page 22: Think Possibility Integrating Web Applications With Databases.

Think Possibility

6) Close the Connection

• To close the database connection:– stmt.close();– connection.close();

• Note: Some application servers, such as BEA WebLogic maintain a pool of database connections.– This is much more efficient, as applications do

not have the overhead of constantly opening and closing database connections.

Page 23: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Designing a Web Application

Using Database• To build a database application you must design the relationship between the Model objects and the corresponding database representation.

• To design the Model elements of an application, you should perform the following tasks:– Design the domain objects of your application– Design the database tables that map to the domain

objects– Design the business services (the Model) to

separate the database code into classes using the DAO pattern.

Page 24: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Case Study: The BasketballLeague

• Domain objects represent the real-world business entities of your application.

objectIDyearseasontitle

objectIDnameaddresscityprovincepostal_code

division

League

Registration

Player* *

Page 25: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Database Tables

• Each domain objects has a corresponding DB table.

LIDyearseasontitle

objectIDnameaddresscityprovincepostal_code

table_nameID_number

<<DB Table>>League

<< DB Table>>ObjectIDs

<<DB Table>>Player* *

LIDPIDdivision

<< DB Table>>Registration

Page 26: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Example Data

Page 27: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Data Access Object (DAO) Pattern

• The DAO pattern makes it easier to maintain applications that use databases by separating the business logic from the data access logic.

• The DAO pattern permits the business logic and the data access logic to change independently.

Page 28: Think Possibility Integrating Web Applications With Databases.

Think Possibility

DAO Pattern Example

+getLeague+getPlayer+register

RegisterService

insert

<<package-private>>PlayerDAO

retrieveinsert

<<package-private>>LeagueDAO

+getLeague+createLeague

RegisterService getNextObjectID

<<package-private>>ObjectIDDAO

Registration servlet

LeagueAdmin servlet

Player

League

Page 29: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Advantages of the DAO Pattern

• Business logic and data access logic are now separate.

• The data access objects promote reuse and flexibility in changing the system.

• Developers writing other servlets can reuse the same data access code.

• This design makes it easy to change front-end technologies.

• This design makes it easy to change back-end technologies.

Page 30: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Using a Connection Pool

• The DAO pattern hides the details of the data access logic from the rest of the system. The DAO classes require connections to access data in a DBMS.

• To develop a Web application that uses a connection pool (CP) with the DAO pattern, consider the ff:– Build or buy a CP subsystem– Store the CP object in a global “name space”– Design your DAOs to use the CP, retrieving it from

the name space– Develop a servlet context listener to initialize the CP

and store it in the name space

Page 31: Think Possibility Integrating Web Applications With Databases.

Think Possibility

Connection Pool