of 40
8/12/2019 Slides DBAccess
1/40
22-Jul-12 1Database Prorgaming with Java
Database Programming with Java
JDBC Basics Basic steps in using JDBC Statement
ResultSet
PreparedStatement
8/12/2019 Slides DBAccess
2/40
22-Jul-12 DatabaseProrgamingwithJava 2
JDBCBasics
JDBC (Java DataBase Connectivity)provides a standard library for
accessing relational databases
JDBC consists of two parts:
o JDBC API, a purely Java-based APIo 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
8/12/2019 Slides DBAccess
3/40
22-Jul-12 3DatabaseProrgamingwithJava
AdvantagesofJDBC
Continued usage of existing data Vendor independent
Platform independent
Ease of use
8/12/2019 Slides DBAccess
4/40
4 types:
Type 1
Type 2
Type 3
Type 4
22-Jul-12 DatabaseProrgamingwithJava 4
JDBCDrivertypes
8/12/2019 Slides DBAccess
5/40
22-Jul-12 Database Prorgaming with Java 5
Type 1: JDBC-ODBC Bridge plus ODBC Driver
This combination provides JDBC access via ODBCdrivers. ODBC binary code -- and in many cases,database client code -- must be loaded on eachclient machine that uses a JDBC-ODBC Bridge.
Example: Sun ODBC
8/12/2019 Slides DBAccess
6/40
AdvantagesThe JDBC-ODBC Bridge allows access to almost anydatabase, 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 alldriver types.
The client system requires the ODBC Installation to
use the driver.
22-Jul-12 DatabaseProrgamingwithJava 6
Type 1: JDBC-ODBC Bridge plus ODBC Driver
8/12/2019 Slides DBAccess
7/40
This type of driver converts JDBC calls into callson 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 DatabaseProrgamingwithJava 7
Type 2: A native API partly Java technology
8/12/2019 Slides DBAccess
8/40
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 aportability issue.
If we change the Database we have to change the
native api as it is specific to a database
22-Jul-12 DatabaseProrgamingwithJava 8
Type 2: A native API partly Java technology
8/12/2019 Slides DBAccess
9/40
Type 3 database requests are passed throughthe network to the middle-tier server. The
middle-tier then translates the request to the
database
22-Jul-12 DatabaseProrgamingwithJava 9
Type 3: All Java/Net-protocol driver
8/12/2019 Slides DBAccess
10/40
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 DatabaseProrgamingwithJava 10
Type 3: All Java/Net-protocol driver
8/12/2019 Slides DBAccess
11/40
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 DatabaseProrgamingwithJava 11
Type 3: All Java/Net-protocol driver
8/12/2019 Slides DBAccess
12/40
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 DatabaseProrgamingwithJava 12
Type 3: All Java/Net-protocol driver
8/12/2019 Slides DBAccess
13/40
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 practicalsolution for intranet access.
22-Jul-12 DatabaseProrgamingwithJava 13
Type 4: Direct-to-Database Pure Java Driver
8/12/2019 Slides DBAccess
14/40
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 DatabaseProrgamingwithJava 14
Type 4: Direct-to-Database Pure Java Driver
8/12/2019 Slides DBAccess
15/40
DisadvantagesWith type 4 drivers, the user needs a different driver
for each database.
22-Jul-12 DatabaseProrgamingwithJava 15
Type 4: Direct-to-Database Pure Java Driver
8/12/2019 Slides DBAccess
16/4022-Jul-12DatabaseProrgamingwithJava 16
JDBCDrivertypes(Sumary)
8/12/2019 Slides DBAccess
17/4022-Jul-12DatabaseProrgamingwithJava 17
Basic Steps in using JDBC
1. Load the driver2. Define the connection URL and establish the
connection
3. Create a Statement object
4. Executing the Statement5. Getting data from executing result
6. Process the results.
7. Close the connection
8/12/2019 Slides DBAccess
18/4022-Jul-12 DatabaseProrgamingwithJava 18
Loading JDBC drivers
Class.forName("DriverXYZ");o Use Class.forName() to load the Driver classo 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);
8/12/2019 Slides DBAccess
19/4022-Jul-12 DatabaseProrgamingwithJava 19
Establish the DB connection
Need to know which database to connect too 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/bookso jdbc:sqlserver://localhost:1433;database = schoolManagement;user=sa;password=1234567";
8/12/2019 Slides DBAccess
20/4022-Jul-12 DatabaseProrgamingwithJava 20
JDBC Statement Object
A Statement object is what sends your SQLstatement 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 );
8/12/2019 Slides DBAccess
21/4022-Jul-12 DatabaseProrgamingwithJava 21
ResultSet object
A ResultSet object is a table of data representing adatabase result set, which is usually generated by
executing a statement that queries the database.
You access the data in a ResultSet object through acursor. This cursor is a pointer that points to one
row of data in the ResultSet. Initially, the cursor is
positioned before the first row.
8/12/2019 Slides DBAccess
22/4022-Jul-12 DatabaseProrgamingwithJava 22
ResultSet type
TYPE_FORWARD_ONLY:The result set cannot be scrolled; its cursor moves forward only, frobefore the first row to after the last row.
TYPE_SCROLL_INSENSITIVE:The result can be scrolled; its cursor can move both forward andbackward relative to the current position, and it can move to anabsolute position.
TYPE_SCROLL_SENSITIVE:The result can be scrolledThe result set reflects changes made to theunderlying data source while the result set remains open.
The default ResultSet type is TYPE_FORWARD_ONLY.
8/12/2019 Slides DBAccess
23/4022-Jul-12 DatabaseProrgamingwithJava 23
ResultSet Concurrency
The concurrency of a ResultSet object determineswhat level of update functionality is supported.
There are two concurrency levels:
CONCUR_READ_ONLY: The ResultSet object cannot beupdated using the ResultSet interface.
CONCUR_UPDATABLE: The ResultSet object can beupdated using the ResultSet interface.
The default ResultSet concurrency isCONCUR_READ_ONLY.
8/12/2019 Slides DBAccess
24/40
22-Jul-12 DatabaseProrgamingwithJava 24
ResultSet navigation
Method Descriptionnext() 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.
8/12/2019 Slides DBAccess
25/40
22-Jul-12 DatabaseProrgamingwithJava 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.
8/12/2019 Slides DBAccess
26/40
22-Jul-12 DatabaseProrgamingwithJava 26
Methods of returning Scrollable ResultSet
public StatementreateStatement(int resultSetType,int resultSetConcurrency) throws SQLException
public PreparedStatement
prepareStatement(Stringsql, int resultSetType,int resultSetConcurrency) throws SQLException
public CallableStatementprepareCall(Stringsql,
int resultSetType, int resultSetConcurrency) throwsSQLException
http://localhost/var/Program%20Files/Java/docs/api/java/sql/Statement.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/sql/SQLException.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/sql/PreparedStatement.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/lang/String.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/sql/SQLException.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/sql/CallableStatement.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/lang/String.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/sql/SQLException.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/sql/SQLException.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/lang/String.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/sql/CallableStatement.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/sql/SQLException.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/lang/String.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/sql/PreparedStatement.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/sql/SQLException.htmlhttp://localhost/var/Program%20Files/Java/docs/api/java/sql/Statement.html8/12/2019 Slides DBAccess
27/40
22-Jul-12 DatabaseProrgamingwithJava 27
Retrieving Column Values from Rows
The ResultSet declares methods (example:getBoolean, getLong, ) for retrieving columnvalues from the current row.
Retrieve values using either the index numberorthe aliasor 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
8/12/2019 Slides DBAccess
28/40
22-Jul-12 DatabaseProrgamingwithJava 28
Updating Rows in ResultSet Objects
With CONCUR_UPDATABLE ResultSet, you canupdate values using updateXXX() method.
Must call the method ResultSet.updateRow toupdate the database.
8/12/2019 Slides DBAccess
29/40
22-Jul-12 DatabaseProrgamingwithJava 29
Inserting a row
Step 1: Positioning the CursorStatement st =
cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE)
ResultSet rs = st.executeQuery(SELECT NAME, EMPLOEE_
FROM EMPLOYEES);
rs.first();
Step 2: Updating the columns: rs.update
Step 3: inserting a row :rs.insertRow();
8/12/2019 Slides DBAccess
30/40
22-Jul-12 DatabaseProrgamingwithJava 30
Example: Inserting Rowstry {
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 ) {
8/12/2019 Slides DBAccess
31/40
22-Jul-12 DatabaseProrgamingwithJava 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();
8/12/2019 Slides DBAccess
32/40
22-Jul-12 DatabaseProrgamingwithJava 32
Connecting & Querying sample Database
DisplayAuthorso Retrieves the entire authorstable
o Displays the data in a JTextArea
8/12/2019 Slides DBAccess
33/40
22-Jul-12 DatabaseProrgamingwithJava 33
DisplayAuthors.java
1 // DisplayAuthors.java
2 // Displaying the contents of the authors table.3 importjava.awt.*;5 importjava.sql.*;6 importjava.util.*;7 importjavax.swing.*;89publicclassDisplayAuthors extendsJFrame {1011 // JDBC driver name and database URL12 staticString JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";13 String DATABASE_URL = "jdbc:oracle:thin:@localhost:1521:orcl";1415 // declare Connection and Statement for accessing16 // and querying database17privateConnection connection;
18privateStatement statement;1920 // constructor connects to database, queries database, processes21 // results and displays results in window22publicDisplayAuthors()23 {24 super( "Authors Table of Books Database");
25
8/12/2019 Slides DBAccess
34/40
22-Jul-12 DatabaseProrgamingwithJava 34
DisplayAuthors.java26 // connect to database books and query database
27 try{28293032 // load database driver class33 Class.forName( JDBC_DRIVER);34
35 // establish connection to database36 connection = DriverManager.getConnection( DATABASE_URL);3738 // create Statement for querying database39 statement = connection.createStatement();4041 // query database
42 ResultSet resultSet =43 statement.executeQuery( "SELECT * FROM authors");4445 // process query results46 StringBuffer results = newStringBuffer();47 ResultSetMetaData metaData = resultSet.getMetaData();48 intnumberOfColumns = metaData.getColumnCount();
49
8/12/2019 Slides DBAccess
35/40
22-Jul-12 DatabaseProrgamingwithJava 35
DisplayAuthors.java50 for( inti = 1; i
8/12/2019 Slides DBAccess
36/40
22-Jul-12 DatabaseProrgamingwithJava 36
DisplayAuthors.java74 // detect problems interacting with the database
75 catch( SQLException sqlException ) {76 JOptionPane.showMessageDialog( null, sqlException.getMessage(),77 "Database Error", JOptionPane.ERROR_MESSAGE );7879 System.exit( 1);80 }8182 // detect problems loading database driver
83 catch( ClassNotFoundException classNotFound ) {84 JOptionPane.showMessageDialog( null, classNotFound.getMessage(),85 "Driver Not Found", JOptionPane.ERROR_MESSAGE);8687 System.exit( 1);88 }89
90 // ensure statement and connection are closed properly91 finally{9293 try{94 statement.close();95 connection.close();96 }97
8/12/2019 Slides DBAccess
37/40
22-Jul-12 DatabaseProrgamingwithJava 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 );103104 System.exit( 1);105 }106 }
107108 } // end DisplayAuthors constructor109110 // launch the application111publicstaticvoidmain( String args[] )112 {113 DisplayAuthors window = newDisplayAuthors();114window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
115 }116117 } // end class DisplayAuthors
8/12/2019 Slides DBAccess
38/40
22-Jul-12 DatabaseProrgamingwithJava 38
PreparedStatement Object
An object that represents a precompiledSQLstatement.
PreparedStatement object is given an SQL
statement when it is created
When the PreparedStatement is executed, theDBMS can just run the PreparedStatement 's
SQL statement without having to compile it first.
PreparedStatement objects are used more forSQL statements that take parameters.
8/12/2019 Slides DBAccess
39/40
22-Jul-12 DatabaseProrgamingwithJava 39
PreparedStatement Example
PreparedStatement pstmt = con.prepareStatement("UPDATE authorsSET lastName = ?WHERE authorID = ?");
pstmt.setString(1, John);pstmt.setInt(2, 3);
pstmt.executeUpdate();
Set value John to the first placeholder. Set value 3to the second placeholder.
8/12/2019 Slides DBAccess
40/40
Assignments
Assignment1
Assignment2
(See assignemt file)