You are on page 1of 40

22-Jul-12

1
Database Prorgaming with Java
Database Programming with Java
JDBC Basics
Basic steps in using JDBC
Statement
ResultSet
PreparedStatement


22-Jul-12
Database Prorgaming with Java
2

JDBC Basics
JDBC (Java DataBase Connectivity)
provides a standard library for
accessing relational databases
JDBC consists of two parts:
o JDBC API, a purely Java-based API
o JDBC Driver Manager,which
communicates with vendor-specific
drivers that perform the real
communication with the database.
JDBC classes are in the java.sql
package
Current JDBC version: 3.0

22-Jul-12 3
Database Prorgaming with Java
Advantages of JDBC
Continued usage of existing data
Vendor independent
Platform independent
Ease of use

4 types:
Type 1
Type 2
Type 3
Type 4


22-Jul-12
Database Prorgaming with Java
4
JDBC Driver types
22-Jul-12
Database Prorgaming with Java
5
Type 1: JDBC-ODBC Bridge plus ODBC Driver

This combination provides JDBC access via ODBC
drivers. ODBC binary code -- and in many cases,
database client code -- must be loaded on each
client machine that uses a JDBC-ODBC Bridge.
Example: Sun ODBC
Advantages
The JDBC-ODBC Bridge allows access to almost any
database, since the database's ODBC drivers are
already available.
Disadvantages
Since the Bridge driver is not written fully in Java,
type 1 drivers are not portable.
A performance issue is. They are the slowest of all
driver types.
The client system requires the ODBC Installation to
use the driver.
22-Jul-12
Database Prorgaming with Java
6
Type 1: JDBC-ODBC Bridge plus ODBC Driver

This type of driver converts JDBC calls into calls
on the client API for Oracle, Sybase, Informix,
DB2, or other DBMS. Note that, like the bridge
driver, this style of driver requires that some
binary code be loaded on each client machine.

22-Jul-12
Database Prorgaming with Java
7
Type 2: A native API partly Java technology
Advantages
The distinctive characteristic of type 2 jdbc drivers are
that they are typically offer better performance than
the JDBC-ODBC Bridge.
Disadvantages
Native API must be installed in the Client System and
hence type 2 drivers cannot be used for the Internet.
Its not written in Java Language which forms a
portability issue.
If we change the Database we have to change the
native api as it is specific to a database

22-Jul-12
Database Prorgaming with Java
8
Type 2: A native API partly Java technology
Type 3 database requests are passed through
the network to the middle-tier server. The
middle-tier then translates the request to the
database
22-Jul-12
Database Prorgaming with Java
9
Type 3: All Java/Net-protocol driver
Advantages
This driver is server-based, so there is no need for
any vendor database library to be present on client
machines.
This driver is fully written in Java and hence
Portable. It is suitable for the web.
There are many opportunities to optimize
portability, performance, and scalability.
The net protocol can be designed to make the client
JDBC driver very small and fast to load.

22-Jul-12
Database Prorgaming with Java
10
Type 3: All Java/Net-protocol driver
The type 3 driver typically provides support for
features such as caching (connections, query results,
and so on), load balancing, and advanced system
administration such as logging and auditing.
This driver is very flexible allows access to multiple
databases using one driver.
They are the most efficient amongst all driver types.
22-Jul-12
Database Prorgaming with Java
11
Type 3: All Java/Net-protocol driver
Disadvantages
It requires another server application to install and
maintain.
Traversing the recordset may take longer, since the
data comes through the backend server.
22-Jul-12
Database Prorgaming with Java
12
Type 3: All Java/Net-protocol driver
This type of driver converts JDBC calls into the
network protocol used directly by DBMSs,
allowing a direct call from the client machine
to the DBMS server and providing a practical
solution for intranet access.
22-Jul-12
Database Prorgaming with Java
13
Type 4: Direct-to-Database Pure Java Driver
Advantages
Type 4 jdbc drivers are completely written in Java to
achieve platform independence and eliminate
deployment administration issues. It is most suitable
for the web.
Type 4 JDBC drivers don't have to translate database
requests to ODBC performance is typically quite
good.
Dont need to install special software on the client
or server.
22-Jul-12
Database Prorgaming with Java
14
Type 4: Direct-to-Database Pure Java Driver
Disadvantages
With type 4 drivers, the user needs a different driver
for each database.
22-Jul-12
Database Prorgaming with Java
15
Type 4: Direct-to-Database Pure Java Driver
22-Jul-12
Database Prorgaming with Java
16
JDBC Driver types(Sumary)
22-Jul-12
Database Prorgaming with Java
17
Basic Steps in using JDBC
1. Load the driver
2. Define the connection URL and establish the
connection
3. Create a Statement object
4. Executing the Statement
5. Getting data from executing result
6. Process the results.
7. Close the connection

22-Jul-12
Database Prorgaming with Java
18
Loading JDBC drivers
Class.forName("DriverXYZ");
o Use Class.forName() to load the Driver class
o No need to register with DriverManager.
Some examples.
o Class.forName("oracle.jdbc.driver.OracleDriver");
o Class.forName("org.gjt.mm.mysql.Driver");
o Class.forName(com.mysql.jdbc.Driver");
o Class.forName(com.ibm.db2j.jdbc.DB2jDriver");
o Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
o Class.forName(com.microsoft.sqlserver.jdbc.SQLServer
Driver);
22-Jul-12
Database Prorgaming with Java
19
Establish the DB connection
Need to know which database to connect to
o In JDBC you need to specify the URL
o Need username, password
Get a java.sql.Connection object
o Connection con = DriverManager.getConnection(url,
user, password);
Examples:
o jdbc:oracle:thin:@localhost:1521:orcl
o jdbc:mysql://127.0.0.1:3306/books
o jdbc:sqlserver://localhost:1433;
database = schoolManagement;
user=sa;password=1234567";
22-Jul-12
Database Prorgaming with Java
20
JDBC Statement Object
A Statement object is what sends your SQL
statement to the DBMS
Create a Statement object and then execute it,
supplying appropriate method with the SQL
statement you want to send.
o Statement stmt = con.createStatement();
For a SELECT statement, the method to use is
executeQuery.
o stmt.executeQuery( SELECT * FROM XXX");
For statements that create or modify tables, the
method to use is executeUpdate.
o stmt.executeUpdate( "INSERT INTO XXX );


22-Jul-12
Database Prorgaming with Java
21
ResultSet object
A ResultSet object is a table of data representing a
database result set, which is usually generated by
executing a statement that queries the database.
You access the data in a ResultSet object through a
cursor. This cursor is a pointer that points to one
row of data in the ResultSet. Initially, the cursor is
positioned before the first row.
22-Jul-12
Database Prorgaming with Java
22
ResultSet type
TYPE_FORWARD_ONLY:
The result set cannot be scrolled; its cursor moves forward only, from
before the first row to after the last row.

TYPE_SCROLL_INSENSITIVE:
The result can be scrolled; its cursor can move both forward and
backward relative to the current position, and it can move to an
absolute position.
TYPE_SCROLL_SENSITIVE:
The result can be scrolledThe result set reflects changes made to the
underlying data source while the result set remains open.

The default ResultSet type is TYPE_FORWARD_ONLY.
22-Jul-12
Database Prorgaming with Java
23
ResultSet Concurrency
The concurrency of a ResultSet object determines
what level of update functionality is supported.
There are two concurrency levels:
CONCUR_READ_ONLY: The ResultSet object cannot be
updated using the ResultSet interface.
CONCUR_UPDATABLE: The ResultSet object can be
updated using the ResultSet interface.
The default ResultSet concurrency is
CONCUR_READ_ONLY.
22-Jul-12
Database Prorgaming with Java
24
ResultSet navigation
Method Description
next() Moves the cursor froward one row from its current position.
previous() Moves the cursor to the previous row in this ResultSet object.
first() Moves the cursor to the first row in this ResultSet object.
last() Moves the cursor to the last row in this ResultSet object.
beforeFirst() Moves the cursor to the front of this ResultSet object, just
before the first row. This method has no effect if the result set
contains no rows.
afterLast() Moves the cursor to the end of this ResultSet object, just after
the last row. This method has no effect if the result set contains
no rows.
getRow() Retrieves the current row number. The first row is number 1, the
second number 2, and so on.
22-Jul-12
Database Prorgaming with Java
25
ResultSet navigation (cont)
Method Description
absolute(int row) Moves the cursor to the given row number in this ResultSet object.
Row number is positive, the cursor moves to the given row
number with respect to the beginning of the result set. The first
row is row 1, the second is row 2, and so on.
row number is negative, the cursor moves to an absolute row
position with respect to the end of the result set. For example,
calling the method absolute(-1) positions the cursor on the last
row; calling the method absolute(-2) moves the cursor to the next-
to-last row, and so on.
relative(int rows) Moves the cursor a relative number of rows, either positive
(forward) or negative (backward).
Note: Calling the method relative(1) is identical to calling the
method next() and calling the method relative(-1) is identical to
calling the method previous(). Calling relative(0) is valid, but does
not change the cursor position.
22-Jul-12
Database Prorgaming with Java
26
Methods of returning Scrollable ResultSet
public Statement reateStatement(int resultSetType,
int resultSetConcurrency) throws SQLException
public PreparedStatement
prepareStatement(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException
public CallableStatement prepareCall(String sql,
int resultSetType, int resultSetConcurrency) throws
SQLException
22-Jul-12
Database Prorgaming with Java
27
Retrieving Column Values from Rows
The ResultSet declares methods (example:
getBoolean, getLong, ) for retrieving column
values from the current row.
Retrieve values using either the index number or
the alias or name of the column.
Columns are numbered from 1.
For maximum portability, result set columns within
each row should be read in left-to-right order
22-Jul-12
Database Prorgaming with Java
28
Updating Rows in ResultSet Objects
With CONCUR_UPDATABLE ResultSet, you can
update values using updateXXX() method.
Must call the method ResultSet.updateRow to
update the database.
22-Jul-12
Database Prorgaming with Java
29
Inserting a row
Step 1: Positioning the Cursor
Statement st =
cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE)
ResultSet rs = st.executeQuery(SELECT NAME, EMPLOEE_ID
FROM EMPLOYEES);
rs.first();
Step 2: Updating the columns: rs.update<Type>
Step 3: inserting a row : rs.insertRow();

22-Jul-12
Database Prorgaming with Java
30
Example: Inserting Rows
try {
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery(
"SELECT * FROM " + dbName + ".COFFEES");

uprs.moveToInsertRow();

uprs.updateString("COF_NAME", coffeeName);
uprs.updateInt("SUP_ID", supplierID);
uprs.updateFloat("PRICE", price);
uprs.updateInt("SALES", sales);
uprs.updateInt("TOTAL", total);

uprs.insertRow();
uprs.beforeFirst();

} catch (SQLException e ) {
22-Jul-12
Database Prorgaming with Java
31
Deleting a row
Step 1: Positioning the cursor
// Move the cursor to the last row of the result set
rs.last();
Step 2: Deleting the row
// Deleting the row from the result set
rs.deleteRow();
22-Jul-12
Database Prorgaming with Java
32
Connecting & Querying sample Database
DisplayAuthors
o Retrieves the entire authors table
o Displays the data in a JTextArea
22-Jul-12
Database Prorgaming with Java
33
DisplayAuthors.java
1 // DisplayAuthors.java
2 // Displaying the contents of the authors table.
3 import java.awt.*;
5 import java.sql.*;
6 import java.util.*;
7 import javax.swing.*;
8
9 public class DisplayAuthors extends JFrame {
10
11 // JDBC driver name and database URL
12 static String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
13 String DATABASE_URL = "jdbc:oracle:thin:@localhost:1521:orcl";
14
15 // declare Connection and Statement for accessing
16 // and querying database
17 private Connection connection;
18 private Statement statement;
19
20 // constructor connects to database, queries database, processes
21 // results and displays results in window
22 public DisplayAuthors()
23 {
24 super( "Authors Table of Books Database" );
25
22-Jul-12
Database Prorgaming with Java
34
DisplayAuthors.java
26 // connect to database books and query database
27 try {
28
29
30
32 // load database driver class
33 Class.forName( JDBC_DRIVER );
34
35 // establish connection to database
36 connection = DriverManager.getConnection( DATABASE_URL );
37
38 // create Statement for querying database
39 statement = connection.createStatement();
40
41 // query database
42 ResultSet resultSet =
43 statement.executeQuery( "SELECT * FROM authors" );
44
45 // process query results
46 StringBuffer results = new StringBuffer();
47 ResultSetMetaData metaData = resultSet.getMetaData();
48 int numberOfColumns = metaData.getColumnCount();
49
22-Jul-12
Database Prorgaming with Java
35
DisplayAuthors.java
50 for ( int i = 1; i <= numberOfColumns; i++ )
51 results.append( metaData.getColumnName( i ) + "\t" );
52
53 results.append( "\n" );
54
55 while ( resultSet.next() ) {
56
57 for ( int i = 1; i <= numberOfColumns; i++ )
58 results.append( resultSet.getObject( i ) + "\t" );
59
60 results.append( "\n" );
61 }
62
63 // set up GUI and display window
64 JTextArea textArea = new JTextArea( results.toString() );
65 Container container = getContentPane();
66
67 container.add( new JScrollPane( textArea ) );
68
69 setSize( 300, 100 ); // set window size
70 setVisible( true ); // display window
71
72 } // end try
73
22-Jul-12
Database Prorgaming with Java
36
DisplayAuthors.java
74 // detect problems interacting with the database
75 catch ( SQLException sqlException ) {
76 JOptionPane.showMessageDialog( null, sqlException.getMessage(),
77 "Database Error", JOptionPane.ERROR_MESSAGE );
78
79 System.exit( 1 );
80 }
81
82 // detect problems loading database driver
83 catch ( ClassNotFoundException classNotFound ) {
84 JOptionPane.showMessageDialog( null, classNotFound.getMessage(),
85 "Driver Not Found", JOptionPane.ERROR_MESSAGE );
86
87 System.exit( 1 );
88 }
89
90 // ensure statement and connection are closed properly
91 finally {
92
93 try {
94 statement.close();
95 connection.close();
96 }
97
22-Jul-12
Database Prorgaming with Java
37
DisplayAuthors.java
98 // handle exceptions closing statement and connection
99 catch ( SQLException sqlException ) {
100 JOptionPane.showMessageDialog( null,
101 sqlException.getMessage(), "Database Error",
102 JOptionPane.ERROR_MESSAGE );
103
104 System.exit( 1 );
105 }
106 }
107
108 } // end DisplayAuthors constructor
109
110 // launch the application
111 public static void main( String args[] )
112 {
113 DisplayAuthors window = new DisplayAuthors();
114 window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
115 }
116
117 } // end class DisplayAuthors
22-Jul-12
Database Prorgaming with Java
38
PreparedStatement Object
An object that represents a precompiled SQL
statement.
PreparedStatement object is given an SQL
statement when it is created
When the PreparedStatement is executed, the
DBMS can just run the PreparedStatement 's
SQL statement without having to compile it first.
PreparedStatement objects are used more for
SQL statements that take parameters.
22-Jul-12
Database Prorgaming with Java
39
PreparedStatement Example
PreparedStatement pstmt = con.prepareStatement(
"UPDATE authors
SET lastName = ?
WHERE authorID = ?");
pstmt.setString(1, John);
pstmt.setInt(2, 3);
pstmt.executeUpdate();

Set value John to the first placeholder.
Set value 3 to the second placeholder.
Assignments
Assignment 1
Assignment 2
(See assignemt file)

22-Jul-12
Database Prorgaming with Java
40

You might also like