Docsity

JDBC and Servlets: Understanding Database Connectivity and Java Servlets in INFS 740 - Pro, Study notes of Database Programming

Partial preview of the text

Download JDBC and Servlets: Understanding Database Connectivity and Java Servlets in INFS 740 - Pro and more Study notes Database Programming in PDF only on Docsity!

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

INFS 740

JDBC & Servlets

Prof. Alex Brodsky

IT&E, GMU

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

JDBC

• JDBC is a specialized API for Java

programs to access RDBMS

Client

JavaApplication

JDBCAPI

JDBC-ODBC

Bridge

ODBC

API

Server ODBCLayer

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

On-line Resources

•^

Sun’s JDBC Site^ – http://java.sun.com/products/jdbc/

•^

JDBC Tutorial^ – http://java.sun.com/docs/books/tutorial/jdbc/

•^

List of Available JDBC Drivers^ – http://industry.java.sun.com/products/jdbc/drivers/

•^

API for java.sql^ – http://java.sun.com/j2se/1.3/docs/api/java/sql/

package-summary.html

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

JDBC Drivers

•^

JDBC consists of two parts:^ – JDBC API, a purely Java-based API– JDBC Driver Manager,which communicates with

vendor-specific drivers that perform the realcommunicationwith the database.

  • Point: translation to vendor format is performed on the client
    • No changes needed to server– Driver (translator) needed in client

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

Seven Basic Steps in

Using JDBC

Load the driver

Define the Connection URL

Establish the Connection

Create a Statement object

Execute a query

Process the results

Close the connection

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

JDBC: Details of Process

Load the driver

try {

Class.forName

("

com.mysql.jdbc.Driver

");

} catch

{

ClassNotFoundException

cnfe)

{

System.out.println("Error loading driver:

" cnfe);

}

Define the Connection URL

String

host

=

“

natalie.emba.uvm.edu";

String dbName

=

"someName";

int port = 1234;String mysqlURL

=

"

jdbc:mysql://

"^

+^

host

":"

port

"/"

dbName

;

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

JDBC: Details of Process, cont.

Create a Statement Statement

statement

=

connection.createStatement();

// discuss

PreparedStatements later

Execute a Query String

query

=

"SELECT

col1,

col2,

col3 FROM sometable";

ResultSet resultSet

=

statement.executeQuery

(query);

–^

To modify

the database, use

executeUpdate

, supplying a string

that uses

UPDATE

,^ INSERT

, or

DELETE

–^

Use

statement.setQueryTimeout

to specify a maximum delay to

wait for results

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

JDBC: Details of Process, cont.

Process the Result

while(resultSet.next()) {System.out.println(resultSet.getString(1) + " " +

resultSet.getString(2) + " " +resultSet.getString(3));

} –

First column has index 1, not 0

-^

ResultSet

provides various

getXxx

methods that take a column index or

name and returns the data

Close the Connection^ connection.close(); –

As opening a connection is expensive, postpone this step if additionaldatabase operations are expected

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

Basic JDBC Example, cont.

Statement s = C.createStatement();String sql="select * from pet";s.execute(sql);ResultSet res=s.getResultSet();if (res!=null)

{

while(res.next()){//note MySql

start with 1

System.out.println("\n"+res.getString(1)

  • "\t"+res.getString(2));

}

} c.close();} catch (SQLException E) {

System.out.println("SQLException: " + E.getMessage());System.out.println("SQLState:

" + E.getSQLState());

System.out.println("VendorError:

" + E.getErrorCode());

}

}

}

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

ResultSet

•^

Overview^ –

A

ResultSet

contains the results of the SQL query

-^

Represented by a table with rows and columns

-^

In JDBC 1.0 you can only proceed forward through the rows using

next

•^

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

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

ResultSet (Continued)

-^

Useful Methods^ –

findColumn

-^

Returns the corresponding integer value corresponding to thespecified column name

-^

Column numbers in the result set do not necessarily map to the samecolumn numbers in the database

–^

getXxx

-^

Returns the value from the column specified bycolumn name or column index as an

Xxx

Java type

-^

Returns 0 or

null (

if the value is a SQL NULL)

-^

Legal

get

Xxx

types:

–^

wasNull

-^

To check if the last

getXxx

read was a SQL

NULL

double

byte

int

Date

String

float

short

long

Time

Object

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

Using MetaData

-^

Idea^ –

From a

ResultSet

(the return type of

executeQuery

), derive a

ResultSetMetaData

object

–^

Use that object to look up the number, names, and types ofcolumns

-^

ResultSetMetaData answers the following questions:^ –

How many columns are in the result set?

-^

What is the name of a given column?

-^

What is the data type of a specific column?

-^

What is the maximum character size of a column?

-^

Etc.

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

Useful MetaData Methods

(Continued)

-^

isNullable^ –

Indicates whether storing a

NULL

in the column is legal

–^

Compare the return value against

ResultSet

constants:

columnNoNulls

,^ columnNullable

,^ columnNullableUnknown

-^

isSearchable^ –

Returns

true

or

false

if the column can be used in a WHERE

clause

-^

isReadOnly/isWritable^ –

The

isReadOnly

method indicates if the column is

definitely not

writable

-^

The

isWritable

method indicates whether it is

possible for a write

to succeed

INFS 740, Prof. A. Brodsky, IT&E, GMU. Based on material developed by Prof. X.Wang, UVM

Using MetaData: Example

Connection connection =DriverManager.getConnection(url, username, password);//

Look up info about the database

as

a whole.

DatabaseMetaData

dbMetaData

=

connection.getMetaData();

String

productName = dbMetaData.

getDatabaseProductName

();

System.out.println("Database: " + productName);String

productVersion = dbMetaData.

getDatabaseProductVersion

();

...Statement

statement = connection.createStatement();

String

query = "SELECT * FROM pet";

ResultSet

resultSet = statement.executeQuery(query);