SlideShare una empresa de Scribd logo
1 de 47
Descargar para leer sin conexión
© Clear View Training 2005 v1.3 1
JDBC
Dr. Jim Arlow
Clear View Training Limited
www.clearviewtraining.com
© Clear View Training 2005 v1.3 2
Copyright notice
This course is Copyright © 2000 Clear View Training Limited.
All rights reserved.
Materials in this course may not be reproduced electronically
or optically without express permission from the copyright
holder. For reprint permissions, contact
Jim.Arlow@clearviewtraining.com
© Clear View Training 2005 v1.3 3
What is JDBC
JDBC, often known as Java
Database Connectivity,
provides a Java API for
updating and querying
relational databases using
Structured Query Language
(SQL)
JDBC is now at version 2.0,
although many databases
don’t as yet support all of
the JDBC 2.0 features!
Java Application
or Applet
JDBC
RDBMS
© Clear View Training 2005 v1.3 4
The 4 step approach to JDBC
Every JDBC program is made up of the
following 4 steps:
Open a connection to the DB
Execute a SQL statement
Process the result
Close the connection to the DB
We’ll look at
each of the
four steps
in detail!
© Clear View Training 2005 v1.3 5
Example JDBC program
1. open connection to DB
2. execute SQL statement
3. process result
4. close connection to DB
1 import java.sql.*;
2 class SelectProducts
3 {
4 public static void main(java.lang.String[ ] args)
5 {
6 try
7 {
8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", " db2admin " );
10 Statement statement = con.createStatement( );
11 ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT");
12 while ( rs.next( ) )
13 {
14 String name = rs.getString( "NAME" );
15 float price = rs.getFloat( "PRICE" );
16 System.out.println("Name: "+name+", price: "+price);
17 }
18 statement.close( );
19 con.close( );
20 }
21 catch( Exception e ) { e.printStackTrace( ); }
22 }
23 }
1
2
3
4
© Clear View Training 2005 v1.3 6
Opening a connection to the DB
There are two parts to this:
loading a driver – we need a driver to allow
our Java program to talk to the DB
opening the connection itself
© Clear View Training 2005 v1.3 7
Loading a driver
The first step in using JDBC is to load a driver.
Here are some examples:
Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
Class.forName( "sun.jdbc.JdbcOdbcDriver" );
The IBM DB2 driver:
The SUN JDBC/ODBC Bridge driver:
© Clear View Training 2005 v1.3 8
There are 4 categories of driver
Type 1 JDBC-ODBC Bridge (Native Code)
provides a Java bridge to ODBC
implemented in native code and requires some non-Java software
on the client
Type 2 Native-API (Partly Java)
uses native code to access the DB with a thin Java wrapper
can crash the JVM
Type 3 Net-protocol (All Java)
defines a generic network protocol that interfaces with some
middleware that accesses the DB
Type 4 Native-protocol (All Java)
written entirely in Java
© Clear View Training 2005 v1.3 9
Type 1 JDBC-ODBC Bridge
Provides a Java bridge to
ODBC
Implemented in native code
and requires some non-
Java software on the client
Not a mandatory
component of the JDK, and
is not automatically
supported by Java run-time
environments
Only recommended for light
use
Java application
ODBC driver
Type 1 JDBC/ODBC
result setSQL command
proprietary
protocol
© Clear View Training 2005 v1.3 10
Type 2 Native API
Converts JDBC commands
into DBMS-specific native
calls
Implemented in native code
and requires some non-
Java software on the client
Interfaces directly with the
DB, so has performance
advantages over Type 1
Java application
Native database library
Type 2 JDBC driver
result setSQL command
proprietary
protocol
© Clear View Training 2005 v1.3 11
Type 3 JDBC-Net drivers
A three tier solution
Allows pure Java clients
Can change DBMS
without affecting the
client
Java application
Type 3 JDBC driver
result setSQL command
proprietary
protocol most flexible
JDBC Driver
Middleware
© Clear View Training 2005 v1.3 12
Type 4 Native Protocol drivers
Native Protocol drivers
communicate directly with
the DB
They convert JDBC
commands directly into the
DB’s native protocol
No additional transformation
or middleware layers,
therefore has high
performance
Java application
Type 4 Pure Java
result set
using
proprietary
protocol
SQL command
using
proprietary
protocol
best
performance
© Clear View Training 2005 v1.3 13
Making a connection
Next, the driver must connect to the DBMS:
The object con gives us an open database
connection
9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", " db2admin " );
DB URL
login password
optional
© Clear View Training 2005 v1.3 14
Creating Statements
A Statement object is used to send SQL
statements to the DB
First we get a Statement object from
our DB connection con
10 Statement statement =con.createStatement( );
© Clear View Training 2005 v1.3 15
Example – creating a table
1 import java.sql.*;
2 class CreateProductTable
3 {
4 public static void main(java.lang.String[ ] args)
5 {
6 try
7 {
8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
9 String url = "jdbc:db2:TEST";
10 Connection con = DriverManager.getConnection( url, "db2admin", "db2admin" );
11 Statement statement = con.createStatement();
12 String createProductTable = "CREATE TABLE PRODUCT " +
13 "(NAME VARCHAR(64), " +
14 "ID VARCHAR(32) NOT NULL, " +
15 "PRICE FLOAT, " +
16 "DESC VARCHAR(256), " +
17 "PRIMARY KEY(ID))";
18 statement.executeUpdate( createProductTable );
19 } catch( Exception e ) { e.printStackTrace(); }
20 }
21 }
© Clear View Training 2005 v1.3 16
executeUpdate(String sql)
Use the executeUpdate() method of the Statement
object to execute DDL and SQL commands that
update a table (INSERT, UPDATE, DELETE):
Be careful to always put spaces in the SQL string at the right places!
12 String createProductTable = "CREATE TABLE PRODUCT " +
13 "(NAME VARCHAR(64), " +
14 "ID VARCHAR(32) NOT NULL, " +
15 "PRICE FLOAT, " +
16 "DESC VARCHAR(256), " +
17 "PRIMARY KEY(ID))";
18 statement.executeUpdate( createProductTable );
© Clear View Training 2005 v1.3 17
Example: inserting rows
1 import java.sql.*;
2 class InsertProducts
3 {
4 public static void main(java.lang.String[ ] args)
5 {
6 try
7 {
8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
9 String url = "jdbc:db2:TEST";
10 Connection con = DriverManager.getConnection( url, "db2admin", " db2admin " );
11 Statement statement = con.createStatement();
12 statement.executeUpdate("INSERT INTO PRODUCT " +
13 "VALUES ( 'UML User Guide', " +
14 "'0-201-57168-4', 47.99, 'The UML user guide')" );
15 statement.executeUpdate("INSERT INTO PRODUCT " +
16 "VALUES ( 'Java Enterprise in a Nutshell', " +
17 "'1-56592-483-5', 29.95, 'A good introduction to J2EE')" );
18 con.close();
19 statement.close();
20 }catch( Exception e ) { e.printStackTrace(); }
21 }
22 }
© Clear View Training 2005 v1.3 18
executeQuery(String sql)
We use the executeQuery(…) method of the
Statement object to execute a SQL statement that
returns a single ResultSet:
11 ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT");
Typically, the SQL statement is a SQL SELECT
executeQuery(…) always returns a ResultSet,
never null. However, the ResultSet may be empty
© Clear View Training 2005 v1.3 19
Example: selecting rows
1 import java.sql.*;
2 class SelectProducts
3 {
4 public static void main(java.lang.String[ ] args)
5 {
6 try
7 {
8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", " db2admin " );
10 Statement statement = con.createStatement();
11 ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT");
12 while ( rs.next( ) )
13 {
14 String name = rs.getString( "NAME" );
15 float price = rs.getFloat( "PRICE" );
16 System.out.println("Name: "+name+", price: "+price);
17 }
18 statement.close();
19 con.close();
20 } catch( Exception e ) { e.printStackTrace(); }
21 }
22 }
© Clear View Training 2005 v1.3 20
ResultSet
ResultSet objects provide access to a table
usually they provide access to the pseudo table that is the result of
a SQL query
ResultSet objects maintain a cursor pointing to the current
row of data
this cursor initially points before the first row and is moved to the
first row by the next() method
11 ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT");
12 while ( rs.next( ) )
13 {
14 String name = rs.getString( "NAME" );
15 float price = rs.getFloat( "PRICE" );
16 System.out.println("Name: "+name+", price: "+price);
17 }
© Clear View Training 2005 v1.3 21
Types of ResultSet
Depending on the parameters passed into the
Connection.createStatement(…) method, we can get
a total of 6 different types of ResultSet returned!
Passing no arguments to createStatement() gives a
default forward-only read-only ResultSet
We’ll look at the possible values for type and
concurrency next…
Statement statement = con.createStatement( type, concurrency);
JDBC
2.0
© Clear View Training 2005 v1.3 22
type
type = semantics
ResultSet.TYPE_SCROLL_SENSITIVE Scrollable. Reflects changes made to
the underlying data
ResultSet.TYPE_SCROLL_INSENSITIVE Scrollable. Does not reflect changes
made to the underlying data
ResultSet.TYPE_FORWARD_ONLY Not scrollable. Does not reflect
changes made to the underlying data
N.B. Scrollable means that we can navigate forwards and
backwards through the ResultSet
JDBC
2.0
© Clear View Training 2005 v1.3 23
concurrency
concurrency = semantics
ResultSet.CONCUR_READ_ONLY
the ResultSet may not be
updated
ResultSet.CONCUR_UPDATABLE
the ResultSet may be
updated
JDBC
2.0
© Clear View Training 2005 v1.3 24
getXXX(…) methods
The ResultSet has a wide range of methods to
return SQL types such as VARCHAR as equivalent
Java types
For example rs.getString(“NAME”) returns the
product name as a String
in fact, we can get any of the SQL types with getString(…)
and it will automatically be converted to a String
The getXXX(…) methods can take a column name or
the number of the column
column numbers start at 1 and go from left to right
see notes!
© Clear View Training 2005 v1.3 25
ResultSet navigation methods
Method Semantics
first() Moves cursor to first row
last() Moves cursor to last row
next() Moves cursor to next row
previous() Moves cursor to previous row
beforeFirst() Moves cursor to just before the first row
afterLast() Moves cursor to just after the last row
absolute(int) Moves cursor to a row index. If positive – counting from
the front, if negative – from the back
relative(int) Moves cursor a relative number of rows, positive or
negative from the current position
JDBC
2.0
© Clear View Training 2005 v1.3 26
Working with ResultSets
We can limit the number of rows that a ResultSet
can contain by using:
Statement statement = con.createStatement();
statement.setMaxRows(100);
If a Statement returns multiple ResultSets, then we
can move to the next ResultSet as follows:
while ( statement.getMoreResults() )
{
rs = statement. getResultSet();
…
© Clear View Training 2005 v1.3 27
Updateable ResultSet
If the statement is created to be of type
ResultSet.CONCUR_UPDATABLE, then we
may be able to update the database by
modifying the ResultSet itself
this may not be supported by all DBMSs as it is
not a mandatory requirement for JDBC 2.0
compatibility
JDBC
2.0
© Clear View Training 2005 v1.3 28
updateXXX(…) methods
Like the getXXX(…) methods, the ResultSet has a
wide range of updateXXX(…) methods to change
the value of SQL types in the ResultSet
For example rs.updateString(“PRICE”, 40.0F)
changes the price of a product
we have to be very careful that that all the types in an
update expression match
The updateXXX(…) methods can take a column
name or the number of the column
column numbers start at 1 and go from left to right
JDBC
2.0
© Clear View Training 2005 v1.3 29
Updating a row
This is a three step procedure:
navigate to the appropriate row using a
SELECT and ResultSet navigation methods
update the field values in the ResultSet
write the change back to the DB
rs.first();
rs.updateFloat("PRICE", 40.0F);
rs.updateRow();
JDBC
2.0
© Clear View Training 2005 v1.3 30
Inserting a row
This is a three step procedure:
navigate to insert row
update the field values in the ResultSet
write the row to the DB
JDBC
2.0
rs.moveToInsertRow();
rs.updateString("NAME", "UML Distilled");
rs.updateString("ID", "0-201-32563-2");
rs.updateFloat("PRICE", 40.0F);
rs.insertRow();
© Clear View Training 2005 v1.3 31
Deleting a row
This is a simple two step procedure:
navigate to row to be deleted
delete the row
JDBC
2.0
rs.last();
rs.deleteRow();
© Clear View Training 2005 v1.3 32
Prepared statements
If we want to execute the same SQL
statement several times, we can create a
PreparedStatement object:
at the point of creation of a PreparedStatement
object the SQL code is sent to the DB and
compiled. Subsequent executions may therefore
be more efficient than normal statements
PreparedStatements can take parameters
© Clear View Training 2005 v1.3 33
Prepared statement example
1 import java.sql.*;
2 class PreparedStatementTest
3 {
4 public static void main(java.lang.String[ ] args)
5 {
6 try
7 {
8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", " db2admin " );
10 PreparedStatement findBooks = con.prepareStatement(
11 "SELECT NAME FROM PRODUCT WHERE NAME LIKE ? " );
12 findBooks.setString( 1, "%Java%" );
13 ResultSet rs = findBooks.executeQuery();
14 while ( rs.next() )
15 { System.out.println("Name: "+ rs.getString( "NAME" ) ); }
16 findBooks.setString( 1, "%UML%" );
17 rs = findBooks.executeQuery();
19 while ( rs.next() )
20 { System.out.println("Name: "+ rs.getString( "NAME" ) ); }
21 findBooks.close();
22 con.close();
23 } catch( Exception e ) { e.printStackTrace(); }
24 }
25 }
© Clear View Training 2005 v1.3 34
Transactions
Normally each SQL statement will be committed
automatically when it has completed executing
(auto commit is on)
A group of statements can be committed together
by turning auto commit off, and explicitly
committing the statements ourselves
This ensures that if any of the statements fail, they
all fail. We can then roll back the transaction
© Clear View Training 2005 v1.3 35
JDBC transaction modes
TRANSACTION_NONE
transactions are disabled or not supported
TRANSACTION_READ_UNCOMITTED
other transactions may see the results before the transaction is committed
“dirty read” - uncommitted rows might be rolled back if the transaction fails.
TRANSACTION_READ_COMMITTED
dirty reads are not allowed.
TRANSACTION_REPEATABLE_READ
if a transaction performs multiple reads on a row that is being changed by another
transaction, then it does not see the changes
TRANSACTION_SERIALIZABLE
same as TRANSACTION_REPEATABLE_READ but also protects against row insertions
if a transaction does a read, another transaction inserts a row, and the first transaction
does another read, the first transaction does not see the new row.
con.setTransactionIsolation( mode )
© Clear View Training 2005 v1.3 36
Transaction example
1 import java.sql.*;
2 class TransactionTest
3 {
4 public static void main(java.lang.String[ ] args)
5 {
6 try
7 {
8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
9 String url = "jdbc:db2:TEST";
10 Connection con = DriverManager.getConnection( url, "db2admin", "db2admin" );
11 Statement s = con.createStatement();
12 try
13 {
14 con.setAutoCommit( false );
15 s.executeUpdate("UPDATE PRODUCT SET PRICE = 40.00 WHERE ID = '0-201-57168-4' " );
16 s.executeUpdate(
17 "UPDATE REVIEW SET COMMENT = 'Now on sale!' WHERE BOOKID = '0-201-57168-4' " );
18 con.commit();
19 }catch( SQLException e ) { con.rollback(); }
20 finally{ con.close(); s.close(); }
21 }catch( Exception e ){ e.printStackTrace(); }
22 }
23 }
© Clear View Training 2005 v1.3 37
Batch updates
JDBC 1.0 was very inefficient for loading a lot of data
into a DB - a separate SQL command had to be
executed for each record changed
JDBC 2.0 allows batch updates
multiple statements can be executed as a single batch
we can roll back the whole batch if a single statement fails
We simply add statements to be batched to a
Statement or PreparedStatement object using
addBatch()!
We can remove the statements using clearBatch()
JDBC
2.0
© Clear View Training 2005 v1.3 38
Batch update example
1 import java.sql.*;
2 class BatchInsertProducts
3 {
4 public static void main(java.lang.String[ ] args) throws SQLException, ClassNotFoundException
5 {
6 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
7 String url = "jdbc:db2:TEST";
8 Connection con = DriverManager.getConnection( url, "db2admin", "db2admin" );
9 Statement s = con.createStatement();
10 try
11 {
12 con.setAutoCommit( false );
13 s.addBatch("INSERT INTO PRODUCT " + "VALUES ( 'The Object Constraint Language', " +
15 "'0-201-37940-4', 29.95, 'All about constraints')" );
16 s.addBatch("INSERT INTO PRODUCT " + "VALUES ( 'The Rational Unified Process', " +
18 "'0-201-60459-0',29.95, 'A good introduction to RUP')" );
19 int[ ] count = s.executeBatch( );
20 con.commit( );
21
22 }catch( SQLException e ) { con.rollback( ); }
23 finally{ con.close( ); s.close( ); }
24 }
25 }
JDBC
2.0
© Clear View Training 2005 v1.3 39
Stored procedures
The syntax for defining a stored procedure is
different for each DBMS
use the stored procedure tools that come with
the RDBMS
The syntax for calling a stored procedure is
different for each DBMS
JDBC defines a special escape sequence syntax
that allows stored procedures to be called in the
same way on any RDBMS
© Clear View Training 2005 v1.3 40
Escape sequences
The ? represents a return value
<procedure-name> is the name of the stored
procedure
<arg1> etc. are the arguments passed into
and out of the stored procedure
{?= call <procedure-name>(<arg1>,<arg2>, …)}
{call <procedure-name>(<arg1>,<arg2>, …)}
© Clear View Training 2005 v1.3 41
Stored procedure example
1 import java.sql.*;
2 class StoredProcedureExample
3 {
4 public static void main(java.lang.String[ ] args)
5 {
6 try
7 {
8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", " db2admin " );
10 CallableStatement cs = con.prepareCall("{call DB2ADMIN.ALLPRODUCTS}");
11 cs.execute();
12 ResultSet rs = cs.getResultSet();
13 while ( rs.next() )
14 {
15 String name = rs.getString( "NAME" );
16 float price = rs.getFloat( "PRICE" );
17 System.out.println("Name: "+name+", price: "+price);
18 }
19 con.close();
20 cs.close();
21 }catch( Exception e ){ e.printStackTrace(); }
22 }
23 }
create a callable
statement
© Clear View Training 2005 v1.3 42
Using input parameters
1 import java.sql.*;
2 class StoredProcedureParameterExample
3 {
4 public static void main(java.lang.String[ ] args)
5 {
6 try
7 {
8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", "db2admin" );
10 CallableStatement cs = con.prepareCall("{call DB2ADMIN.FINDPROD2(?)}");
11 cs.setString( 1, "%UML%" );
12 cs.execute();
13 ResultSet rs = cs.getResultSet();
14 while ( rs.next() )
15 {
16 String name = rs.getString( "NAME" );
17 float price = rs.getFloat( "PRICE" );
18 System.out.println("Name: "+name+", price: "+price);
19 }
20 con.close();
21 cs.close();
22 }catch( Exception e ){ e.printStackTrace(); }
23 }
24 }
we specify a
single parameter
set the
parameter value
© Clear View Training 2005 v1.3 43
Metadata
JDBC has facilities to get information about a
ResultSet or DB
for a ResultSet, this information may include the number
and names of the columns, the types of the columns etc.
for a DB this information may include the name of the
driver, the DB URL etc.
This information about a ResultSet or DB is known as
metadata
See the following classes for details:
ResultSet – see ResultSetMetadata
Database – see DatabaseMetadata
© Clear View Training 2005 v1.3 44
Getting metadata
Getting database metadata:
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT");
ResultSetMetaData rsmd = rs.getMetaData( );
Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", "db2admin" );
DatabaseMetaData dmd = con.getMetaData( );
Getting ResultSet metadata:
© Clear View Training 2005 v1.3 45
Summary
We have looked at:
4 step approach to JDBC
Connection
drivers
Statement
PreparedStatement
batch update
transactions
CallableStatement (stored procedures)
ResultSet handling
Metadata
© Clear View Training 2005 v1.3 46
Appendix: IBM DB2 (v6)
© Clear View Training 2005 v1.3 47
Installing the JDBC 2.0 driver
To install JDBC 2.0:
go to the directory sqllibjava12
run the command usejdbc2
To switch back to 1.2.2:
go to the directory sqllibjava12
run the command usejdbc1

Más contenido relacionado

La actualidad más candente

Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guidePankaj Singh
 
Visage Android - Cleaner APIs, Cleaner UIs
Visage Android - Cleaner APIs, Cleaner UIsVisage Android - Cleaner APIs, Cleaner UIs
Visage Android - Cleaner APIs, Cleaner UIsStephen Chin
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot missMark Papis
 
Haj 4328-java ee 7 overview
Haj 4328-java ee 7 overviewHaj 4328-java ee 7 overview
Haj 4328-java ee 7 overviewKevin Sutter
 
50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutesArun Gupta
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOPHitesh-Java
 
Java interview questions
Java interview questionsJava interview questions
Java interview questionsSoba Arjun
 
JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...Edureka!
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Murat Yener
 

La actualidad más candente (20)

Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Core java
Core javaCore java
Core java
 
Reactjs
ReactjsReactjs
Reactjs
 
Jdbc
JdbcJdbc
Jdbc
 
Visage Android - Cleaner APIs, Cleaner UIs
Visage Android - Cleaner APIs, Cleaner UIsVisage Android - Cleaner APIs, Cleaner UIs
Visage Android - Cleaner APIs, Cleaner UIs
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss
 
Haj 4328-java ee 7 overview
Haj 4328-java ee 7 overviewHaj 4328-java ee 7 overview
Haj 4328-java ee 7 overview
 
DataFX - JavaOne 2013
DataFX - JavaOne 2013DataFX - JavaOne 2013
DataFX - JavaOne 2013
 
Brouchure
BrouchureBrouchure
Brouchure
 
50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
Type script
Type scriptType script
Type script
 

Similar a java arlow jdbc tutorial(java programming tutorials)

Similar a java arlow jdbc tutorial(java programming tutorials) (20)

JDBC
JDBC JDBC
JDBC
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Jdbc new
Jdbc newJdbc new
Jdbc new
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Jdbc
Jdbc   Jdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
Prashanthi
PrashanthiPrashanthi
Prashanthi
 
Lecture17
Lecture17Lecture17
Lecture17
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Chapter vii(accessing databases with jdbc)
Chapter vii(accessing databases with jdbc)Chapter vii(accessing databases with jdbc)
Chapter vii(accessing databases with jdbc)
 

Más de Daroko blog(www.professionalbloggertricks.com)

Más de Daroko blog(www.professionalbloggertricks.com) (20)

Small Business ideas you can start in Nigeria 2014(best Business ideas Nigeri...
Small Business ideas you can start in Nigeria 2014(best Business ideas Nigeri...Small Business ideas you can start in Nigeria 2014(best Business ideas Nigeri...
Small Business ideas you can start in Nigeria 2014(best Business ideas Nigeri...
 
Agriculture business ideas for 2014(Business ideas Kenya,Business ideas Niger...
Agriculture business ideas for 2014(Business ideas Kenya,Business ideas Niger...Agriculture business ideas for 2014(Business ideas Kenya,Business ideas Niger...
Agriculture business ideas for 2014(Business ideas Kenya,Business ideas Niger...
 
An Introduction to Project management(project management tutorials)
An Introduction to Project management(project management tutorials)An Introduction to Project management(project management tutorials)
An Introduction to Project management(project management tutorials)
 
The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)
 
Java programming basics notes for beginners(java programming tutorials)
Java programming basics notes for beginners(java programming tutorials)Java programming basics notes for beginners(java programming tutorials)
Java programming basics notes for beginners(java programming tutorials)
 
advanced java programming(java programming tutorials)
 advanced java programming(java programming tutorials) advanced java programming(java programming tutorials)
advanced java programming(java programming tutorials)
 
java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)
 
An introduction to java programming language forbeginners(java programming tu...
An introduction to java programming language forbeginners(java programming tu...An introduction to java programming language forbeginners(java programming tu...
An introduction to java programming language forbeginners(java programming tu...
 
fundamentals of Computer graphics(Computer graphics tutorials)
 fundamentals of Computer graphics(Computer graphics tutorials) fundamentals of Computer graphics(Computer graphics tutorials)
fundamentals of Computer graphics(Computer graphics tutorials)
 
bresenham circles and polygons in computer graphics(Computer graphics tutorials)
bresenham circles and polygons in computer graphics(Computer graphics tutorials)bresenham circles and polygons in computer graphics(Computer graphics tutorials)
bresenham circles and polygons in computer graphics(Computer graphics tutorials)
 
Computer Graphics display technologies(Computer graphics tutorials and tips)
Computer Graphics display technologies(Computer graphics tutorials and tips)Computer Graphics display technologies(Computer graphics tutorials and tips)
Computer Graphics display technologies(Computer graphics tutorials and tips)
 
Computer Graphics display technologies(Computer graphics tutorials)
Computer Graphics display technologies(Computer graphics tutorials)Computer Graphics display technologies(Computer graphics tutorials)
Computer Graphics display technologies(Computer graphics tutorials)
 
Displays and color system in computer graphics(Computer graphics tutorials)
Displays and color system in computer graphics(Computer graphics tutorials)Displays and color system in computer graphics(Computer graphics tutorials)
Displays and color system in computer graphics(Computer graphics tutorials)
 
Data structures graphics library in computer graphics.
Data structures  graphics library in computer graphics.Data structures  graphics library in computer graphics.
Data structures graphics library in computer graphics.
 
lecture8 clipping
lecture8 clippinglecture8 clipping
lecture8 clipping
 
Csc406 lecture7 device independence and normalization in Computer graphics(Co...
Csc406 lecture7 device independence and normalization in Computer graphics(Co...Csc406 lecture7 device independence and normalization in Computer graphics(Co...
Csc406 lecture7 device independence and normalization in Computer graphics(Co...
 
lecture4 raster details in computer graphics(Computer graphics tutorials)
lecture4 raster details in computer graphics(Computer graphics tutorials)lecture4 raster details in computer graphics(Computer graphics tutorials)
lecture4 raster details in computer graphics(Computer graphics tutorials)
 
lecture3 color representation in computer graphics(Computer graphics tutorials)
lecture3 color representation in computer graphics(Computer graphics tutorials)lecture3 color representation in computer graphics(Computer graphics tutorials)
lecture3 color representation in computer graphics(Computer graphics tutorials)
 
lecture2 computer graphics graphics hardware(Computer graphics tutorials)
 lecture2  computer graphics graphics hardware(Computer graphics tutorials) lecture2  computer graphics graphics hardware(Computer graphics tutorials)
lecture2 computer graphics graphics hardware(Computer graphics tutorials)
 
lecture1 introduction to computer graphics(Computer graphics tutorials)
lecture1 introduction to computer graphics(Computer graphics tutorials)lecture1 introduction to computer graphics(Computer graphics tutorials)
lecture1 introduction to computer graphics(Computer graphics tutorials)
 

Último

Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 

Último (20)

Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 

java arlow jdbc tutorial(java programming tutorials)

  • 1. © Clear View Training 2005 v1.3 1 JDBC Dr. Jim Arlow Clear View Training Limited www.clearviewtraining.com
  • 2. © Clear View Training 2005 v1.3 2 Copyright notice This course is Copyright © 2000 Clear View Training Limited. All rights reserved. Materials in this course may not be reproduced electronically or optically without express permission from the copyright holder. For reprint permissions, contact Jim.Arlow@clearviewtraining.com
  • 3. © Clear View Training 2005 v1.3 3 What is JDBC JDBC, often known as Java Database Connectivity, provides a Java API for updating and querying relational databases using Structured Query Language (SQL) JDBC is now at version 2.0, although many databases don’t as yet support all of the JDBC 2.0 features! Java Application or Applet JDBC RDBMS
  • 4. © Clear View Training 2005 v1.3 4 The 4 step approach to JDBC Every JDBC program is made up of the following 4 steps: Open a connection to the DB Execute a SQL statement Process the result Close the connection to the DB We’ll look at each of the four steps in detail!
  • 5. © Clear View Training 2005 v1.3 5 Example JDBC program 1. open connection to DB 2. execute SQL statement 3. process result 4. close connection to DB 1 import java.sql.*; 2 class SelectProducts 3 { 4 public static void main(java.lang.String[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", " db2admin " ); 10 Statement statement = con.createStatement( ); 11 ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT"); 12 while ( rs.next( ) ) 13 { 14 String name = rs.getString( "NAME" ); 15 float price = rs.getFloat( "PRICE" ); 16 System.out.println("Name: "+name+", price: "+price); 17 } 18 statement.close( ); 19 con.close( ); 20 } 21 catch( Exception e ) { e.printStackTrace( ); } 22 } 23 } 1 2 3 4
  • 6. © Clear View Training 2005 v1.3 6 Opening a connection to the DB There are two parts to this: loading a driver – we need a driver to allow our Java program to talk to the DB opening the connection itself
  • 7. © Clear View Training 2005 v1.3 7 Loading a driver The first step in using JDBC is to load a driver. Here are some examples: Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); Class.forName( "sun.jdbc.JdbcOdbcDriver" ); The IBM DB2 driver: The SUN JDBC/ODBC Bridge driver:
  • 8. © Clear View Training 2005 v1.3 8 There are 4 categories of driver Type 1 JDBC-ODBC Bridge (Native Code) provides a Java bridge to ODBC implemented in native code and requires some non-Java software on the client Type 2 Native-API (Partly Java) uses native code to access the DB with a thin Java wrapper can crash the JVM Type 3 Net-protocol (All Java) defines a generic network protocol that interfaces with some middleware that accesses the DB Type 4 Native-protocol (All Java) written entirely in Java
  • 9. © Clear View Training 2005 v1.3 9 Type 1 JDBC-ODBC Bridge Provides a Java bridge to ODBC Implemented in native code and requires some non- Java software on the client Not a mandatory component of the JDK, and is not automatically supported by Java run-time environments Only recommended for light use Java application ODBC driver Type 1 JDBC/ODBC result setSQL command proprietary protocol
  • 10. © Clear View Training 2005 v1.3 10 Type 2 Native API Converts JDBC commands into DBMS-specific native calls Implemented in native code and requires some non- Java software on the client Interfaces directly with the DB, so has performance advantages over Type 1 Java application Native database library Type 2 JDBC driver result setSQL command proprietary protocol
  • 11. © Clear View Training 2005 v1.3 11 Type 3 JDBC-Net drivers A three tier solution Allows pure Java clients Can change DBMS without affecting the client Java application Type 3 JDBC driver result setSQL command proprietary protocol most flexible JDBC Driver Middleware
  • 12. © Clear View Training 2005 v1.3 12 Type 4 Native Protocol drivers Native Protocol drivers communicate directly with the DB They convert JDBC commands directly into the DB’s native protocol No additional transformation or middleware layers, therefore has high performance Java application Type 4 Pure Java result set using proprietary protocol SQL command using proprietary protocol best performance
  • 13. © Clear View Training 2005 v1.3 13 Making a connection Next, the driver must connect to the DBMS: The object con gives us an open database connection 9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", " db2admin " ); DB URL login password optional
  • 14. © Clear View Training 2005 v1.3 14 Creating Statements A Statement object is used to send SQL statements to the DB First we get a Statement object from our DB connection con 10 Statement statement =con.createStatement( );
  • 15. © Clear View Training 2005 v1.3 15 Example – creating a table 1 import java.sql.*; 2 class CreateProductTable 3 { 4 public static void main(java.lang.String[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 String url = "jdbc:db2:TEST"; 10 Connection con = DriverManager.getConnection( url, "db2admin", "db2admin" ); 11 Statement statement = con.createStatement(); 12 String createProductTable = "CREATE TABLE PRODUCT " + 13 "(NAME VARCHAR(64), " + 14 "ID VARCHAR(32) NOT NULL, " + 15 "PRICE FLOAT, " + 16 "DESC VARCHAR(256), " + 17 "PRIMARY KEY(ID))"; 18 statement.executeUpdate( createProductTable ); 19 } catch( Exception e ) { e.printStackTrace(); } 20 } 21 }
  • 16. © Clear View Training 2005 v1.3 16 executeUpdate(String sql) Use the executeUpdate() method of the Statement object to execute DDL and SQL commands that update a table (INSERT, UPDATE, DELETE): Be careful to always put spaces in the SQL string at the right places! 12 String createProductTable = "CREATE TABLE PRODUCT " + 13 "(NAME VARCHAR(64), " + 14 "ID VARCHAR(32) NOT NULL, " + 15 "PRICE FLOAT, " + 16 "DESC VARCHAR(256), " + 17 "PRIMARY KEY(ID))"; 18 statement.executeUpdate( createProductTable );
  • 17. © Clear View Training 2005 v1.3 17 Example: inserting rows 1 import java.sql.*; 2 class InsertProducts 3 { 4 public static void main(java.lang.String[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 String url = "jdbc:db2:TEST"; 10 Connection con = DriverManager.getConnection( url, "db2admin", " db2admin " ); 11 Statement statement = con.createStatement(); 12 statement.executeUpdate("INSERT INTO PRODUCT " + 13 "VALUES ( 'UML User Guide', " + 14 "'0-201-57168-4', 47.99, 'The UML user guide')" ); 15 statement.executeUpdate("INSERT INTO PRODUCT " + 16 "VALUES ( 'Java Enterprise in a Nutshell', " + 17 "'1-56592-483-5', 29.95, 'A good introduction to J2EE')" ); 18 con.close(); 19 statement.close(); 20 }catch( Exception e ) { e.printStackTrace(); } 21 } 22 }
  • 18. © Clear View Training 2005 v1.3 18 executeQuery(String sql) We use the executeQuery(…) method of the Statement object to execute a SQL statement that returns a single ResultSet: 11 ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT"); Typically, the SQL statement is a SQL SELECT executeQuery(…) always returns a ResultSet, never null. However, the ResultSet may be empty
  • 19. © Clear View Training 2005 v1.3 19 Example: selecting rows 1 import java.sql.*; 2 class SelectProducts 3 { 4 public static void main(java.lang.String[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", " db2admin " ); 10 Statement statement = con.createStatement(); 11 ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT"); 12 while ( rs.next( ) ) 13 { 14 String name = rs.getString( "NAME" ); 15 float price = rs.getFloat( "PRICE" ); 16 System.out.println("Name: "+name+", price: "+price); 17 } 18 statement.close(); 19 con.close(); 20 } catch( Exception e ) { e.printStackTrace(); } 21 } 22 }
  • 20. © Clear View Training 2005 v1.3 20 ResultSet ResultSet objects provide access to a table usually they provide access to the pseudo table that is the result of a SQL query ResultSet objects maintain a cursor pointing to the current row of data this cursor initially points before the first row and is moved to the first row by the next() method 11 ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT"); 12 while ( rs.next( ) ) 13 { 14 String name = rs.getString( "NAME" ); 15 float price = rs.getFloat( "PRICE" ); 16 System.out.println("Name: "+name+", price: "+price); 17 }
  • 21. © Clear View Training 2005 v1.3 21 Types of ResultSet Depending on the parameters passed into the Connection.createStatement(…) method, we can get a total of 6 different types of ResultSet returned! Passing no arguments to createStatement() gives a default forward-only read-only ResultSet We’ll look at the possible values for type and concurrency next… Statement statement = con.createStatement( type, concurrency); JDBC 2.0
  • 22. © Clear View Training 2005 v1.3 22 type type = semantics ResultSet.TYPE_SCROLL_SENSITIVE Scrollable. Reflects changes made to the underlying data ResultSet.TYPE_SCROLL_INSENSITIVE Scrollable. Does not reflect changes made to the underlying data ResultSet.TYPE_FORWARD_ONLY Not scrollable. Does not reflect changes made to the underlying data N.B. Scrollable means that we can navigate forwards and backwards through the ResultSet JDBC 2.0
  • 23. © Clear View Training 2005 v1.3 23 concurrency concurrency = semantics ResultSet.CONCUR_READ_ONLY the ResultSet may not be updated ResultSet.CONCUR_UPDATABLE the ResultSet may be updated JDBC 2.0
  • 24. © Clear View Training 2005 v1.3 24 getXXX(…) methods The ResultSet has a wide range of methods to return SQL types such as VARCHAR as equivalent Java types For example rs.getString(“NAME”) returns the product name as a String in fact, we can get any of the SQL types with getString(…) and it will automatically be converted to a String The getXXX(…) methods can take a column name or the number of the column column numbers start at 1 and go from left to right see notes!
  • 25. © Clear View Training 2005 v1.3 25 ResultSet navigation methods Method Semantics first() Moves cursor to first row last() Moves cursor to last row next() Moves cursor to next row previous() Moves cursor to previous row beforeFirst() Moves cursor to just before the first row afterLast() Moves cursor to just after the last row absolute(int) Moves cursor to a row index. If positive – counting from the front, if negative – from the back relative(int) Moves cursor a relative number of rows, positive or negative from the current position JDBC 2.0
  • 26. © Clear View Training 2005 v1.3 26 Working with ResultSets We can limit the number of rows that a ResultSet can contain by using: Statement statement = con.createStatement(); statement.setMaxRows(100); If a Statement returns multiple ResultSets, then we can move to the next ResultSet as follows: while ( statement.getMoreResults() ) { rs = statement. getResultSet(); …
  • 27. © Clear View Training 2005 v1.3 27 Updateable ResultSet If the statement is created to be of type ResultSet.CONCUR_UPDATABLE, then we may be able to update the database by modifying the ResultSet itself this may not be supported by all DBMSs as it is not a mandatory requirement for JDBC 2.0 compatibility JDBC 2.0
  • 28. © Clear View Training 2005 v1.3 28 updateXXX(…) methods Like the getXXX(…) methods, the ResultSet has a wide range of updateXXX(…) methods to change the value of SQL types in the ResultSet For example rs.updateString(“PRICE”, 40.0F) changes the price of a product we have to be very careful that that all the types in an update expression match The updateXXX(…) methods can take a column name or the number of the column column numbers start at 1 and go from left to right JDBC 2.0
  • 29. © Clear View Training 2005 v1.3 29 Updating a row This is a three step procedure: navigate to the appropriate row using a SELECT and ResultSet navigation methods update the field values in the ResultSet write the change back to the DB rs.first(); rs.updateFloat("PRICE", 40.0F); rs.updateRow(); JDBC 2.0
  • 30. © Clear View Training 2005 v1.3 30 Inserting a row This is a three step procedure: navigate to insert row update the field values in the ResultSet write the row to the DB JDBC 2.0 rs.moveToInsertRow(); rs.updateString("NAME", "UML Distilled"); rs.updateString("ID", "0-201-32563-2"); rs.updateFloat("PRICE", 40.0F); rs.insertRow();
  • 31. © Clear View Training 2005 v1.3 31 Deleting a row This is a simple two step procedure: navigate to row to be deleted delete the row JDBC 2.0 rs.last(); rs.deleteRow();
  • 32. © Clear View Training 2005 v1.3 32 Prepared statements If we want to execute the same SQL statement several times, we can create a PreparedStatement object: at the point of creation of a PreparedStatement object the SQL code is sent to the DB and compiled. Subsequent executions may therefore be more efficient than normal statements PreparedStatements can take parameters
  • 33. © Clear View Training 2005 v1.3 33 Prepared statement example 1 import java.sql.*; 2 class PreparedStatementTest 3 { 4 public static void main(java.lang.String[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", " db2admin " ); 10 PreparedStatement findBooks = con.prepareStatement( 11 "SELECT NAME FROM PRODUCT WHERE NAME LIKE ? " ); 12 findBooks.setString( 1, "%Java%" ); 13 ResultSet rs = findBooks.executeQuery(); 14 while ( rs.next() ) 15 { System.out.println("Name: "+ rs.getString( "NAME" ) ); } 16 findBooks.setString( 1, "%UML%" ); 17 rs = findBooks.executeQuery(); 19 while ( rs.next() ) 20 { System.out.println("Name: "+ rs.getString( "NAME" ) ); } 21 findBooks.close(); 22 con.close(); 23 } catch( Exception e ) { e.printStackTrace(); } 24 } 25 }
  • 34. © Clear View Training 2005 v1.3 34 Transactions Normally each SQL statement will be committed automatically when it has completed executing (auto commit is on) A group of statements can be committed together by turning auto commit off, and explicitly committing the statements ourselves This ensures that if any of the statements fail, they all fail. We can then roll back the transaction
  • 35. © Clear View Training 2005 v1.3 35 JDBC transaction modes TRANSACTION_NONE transactions are disabled or not supported TRANSACTION_READ_UNCOMITTED other transactions may see the results before the transaction is committed “dirty read” - uncommitted rows might be rolled back if the transaction fails. TRANSACTION_READ_COMMITTED dirty reads are not allowed. TRANSACTION_REPEATABLE_READ if a transaction performs multiple reads on a row that is being changed by another transaction, then it does not see the changes TRANSACTION_SERIALIZABLE same as TRANSACTION_REPEATABLE_READ but also protects against row insertions if a transaction does a read, another transaction inserts a row, and the first transaction does another read, the first transaction does not see the new row. con.setTransactionIsolation( mode )
  • 36. © Clear View Training 2005 v1.3 36 Transaction example 1 import java.sql.*; 2 class TransactionTest 3 { 4 public static void main(java.lang.String[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 String url = "jdbc:db2:TEST"; 10 Connection con = DriverManager.getConnection( url, "db2admin", "db2admin" ); 11 Statement s = con.createStatement(); 12 try 13 { 14 con.setAutoCommit( false ); 15 s.executeUpdate("UPDATE PRODUCT SET PRICE = 40.00 WHERE ID = '0-201-57168-4' " ); 16 s.executeUpdate( 17 "UPDATE REVIEW SET COMMENT = 'Now on sale!' WHERE BOOKID = '0-201-57168-4' " ); 18 con.commit(); 19 }catch( SQLException e ) { con.rollback(); } 20 finally{ con.close(); s.close(); } 21 }catch( Exception e ){ e.printStackTrace(); } 22 } 23 }
  • 37. © Clear View Training 2005 v1.3 37 Batch updates JDBC 1.0 was very inefficient for loading a lot of data into a DB - a separate SQL command had to be executed for each record changed JDBC 2.0 allows batch updates multiple statements can be executed as a single batch we can roll back the whole batch if a single statement fails We simply add statements to be batched to a Statement or PreparedStatement object using addBatch()! We can remove the statements using clearBatch() JDBC 2.0
  • 38. © Clear View Training 2005 v1.3 38 Batch update example 1 import java.sql.*; 2 class BatchInsertProducts 3 { 4 public static void main(java.lang.String[ ] args) throws SQLException, ClassNotFoundException 5 { 6 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 7 String url = "jdbc:db2:TEST"; 8 Connection con = DriverManager.getConnection( url, "db2admin", "db2admin" ); 9 Statement s = con.createStatement(); 10 try 11 { 12 con.setAutoCommit( false ); 13 s.addBatch("INSERT INTO PRODUCT " + "VALUES ( 'The Object Constraint Language', " + 15 "'0-201-37940-4', 29.95, 'All about constraints')" ); 16 s.addBatch("INSERT INTO PRODUCT " + "VALUES ( 'The Rational Unified Process', " + 18 "'0-201-60459-0',29.95, 'A good introduction to RUP')" ); 19 int[ ] count = s.executeBatch( ); 20 con.commit( ); 21 22 }catch( SQLException e ) { con.rollback( ); } 23 finally{ con.close( ); s.close( ); } 24 } 25 } JDBC 2.0
  • 39. © Clear View Training 2005 v1.3 39 Stored procedures The syntax for defining a stored procedure is different for each DBMS use the stored procedure tools that come with the RDBMS The syntax for calling a stored procedure is different for each DBMS JDBC defines a special escape sequence syntax that allows stored procedures to be called in the same way on any RDBMS
  • 40. © Clear View Training 2005 v1.3 40 Escape sequences The ? represents a return value <procedure-name> is the name of the stored procedure <arg1> etc. are the arguments passed into and out of the stored procedure {?= call <procedure-name>(<arg1>,<arg2>, …)} {call <procedure-name>(<arg1>,<arg2>, …)}
  • 41. © Clear View Training 2005 v1.3 41 Stored procedure example 1 import java.sql.*; 2 class StoredProcedureExample 3 { 4 public static void main(java.lang.String[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", " db2admin " ); 10 CallableStatement cs = con.prepareCall("{call DB2ADMIN.ALLPRODUCTS}"); 11 cs.execute(); 12 ResultSet rs = cs.getResultSet(); 13 while ( rs.next() ) 14 { 15 String name = rs.getString( "NAME" ); 16 float price = rs.getFloat( "PRICE" ); 17 System.out.println("Name: "+name+", price: "+price); 18 } 19 con.close(); 20 cs.close(); 21 }catch( Exception e ){ e.printStackTrace(); } 22 } 23 } create a callable statement
  • 42. © Clear View Training 2005 v1.3 42 Using input parameters 1 import java.sql.*; 2 class StoredProcedureParameterExample 3 { 4 public static void main(java.lang.String[ ] args) 5 { 6 try 7 { 8 Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); 9 Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", "db2admin" ); 10 CallableStatement cs = con.prepareCall("{call DB2ADMIN.FINDPROD2(?)}"); 11 cs.setString( 1, "%UML%" ); 12 cs.execute(); 13 ResultSet rs = cs.getResultSet(); 14 while ( rs.next() ) 15 { 16 String name = rs.getString( "NAME" ); 17 float price = rs.getFloat( "PRICE" ); 18 System.out.println("Name: "+name+", price: "+price); 19 } 20 con.close(); 21 cs.close(); 22 }catch( Exception e ){ e.printStackTrace(); } 23 } 24 } we specify a single parameter set the parameter value
  • 43. © Clear View Training 2005 v1.3 43 Metadata JDBC has facilities to get information about a ResultSet or DB for a ResultSet, this information may include the number and names of the columns, the types of the columns etc. for a DB this information may include the name of the driver, the DB URL etc. This information about a ResultSet or DB is known as metadata See the following classes for details: ResultSet – see ResultSetMetadata Database – see DatabaseMetadata
  • 44. © Clear View Training 2005 v1.3 44 Getting metadata Getting database metadata: Statement statement = con.createStatement(); ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT"); ResultSetMetaData rsmd = rs.getMetaData( ); Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", "db2admin" ); DatabaseMetaData dmd = con.getMetaData( ); Getting ResultSet metadata:
  • 45. © Clear View Training 2005 v1.3 45 Summary We have looked at: 4 step approach to JDBC Connection drivers Statement PreparedStatement batch update transactions CallableStatement (stored procedures) ResultSet handling Metadata
  • 46. © Clear View Training 2005 v1.3 46 Appendix: IBM DB2 (v6)
  • 47. © Clear View Training 2005 v1.3 47 Installing the JDBC 2.0 driver To install JDBC 2.0: go to the directory sqllibjava12 run the command usejdbc2 To switch back to 1.2.2: go to the directory sqllibjava12 run the command usejdbc1