2 Best-JDBC Final
2 Best-JDBC Final
1
DriverManager class : Loads the driver for the
database.
1. Load a driver
2. Connect to a database
3. Create and execute JDBC statements
4. Handle SQL exceptions
3
Loading a Driver
The first step to develop a JDBC application is to load
and register the required driver using the driver
manager .
1. Programmatically :
2. Manually:
4 . By setting system property
Using the forName () Method
The forName() method is available in the
java.lang.Class class.
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
5
Using the registerDriver () method
You can create an instance of the Driver class to load a JDBC driver.
Once you have created the Driver object ,call the registerDriver ()
method to register it with the DriverManager.
You can register the JDBC-ODBC Bridge driver using the following
method call to registerDriver () method:
DriverManager.registerDriver (d) ;
6
Setting System Property
Driver can also be loaded by setting system property for JDBC
drivers.
You add the driver name to the jdbc.drivers system property to load
a JDBC driver.
You use the –D command line option to set the system property on
the command line.
7
After you load a driver , you need to establish the connection with a
Connecting to a Database
You create an object of the Connection interface to establish a
connection with a database.
The syntax for the JDBC url that is passed as a parameter to the
getConnection() method is :
<protocol>:<subprotocol>:<subname>
p.setProperty(“user” , “Newuser”);
p.setProperty(“password”,”NewPassword”);
11
The Statement interface contains the following methods to send
static statements to a database:
You can use the DML statements , INSERT , UPDATE and DELETE , in
Java applications to modify the data stored in the databasetables.
You can also use the DDL statements, CREATE, ALTER and DROP in
java applications to define or change the structure of database
objects.
13
Querying a Table
ResultSet rs = stmt.executeQuery(str);
14 ResultSet rs = stmt.executeQuery(str);
Handling SQL Exceptions
The java.sql package provides the SQLException class , which is
derived from the java.lang.Exception class.
You can catch the SQLException in a Java application using the try
and catch exception handling block.
16
Result Sets
When you execute a query to retrieve data from a table using a
java application , the output of the query is stored in a ResultSet
object in a tabular format.
As a result , it moves from the first row to the last row in the
ResultSet.
The cursor in the ResultSet object initially points before the first
row
17
Type of Results Sets
Read only : Allows you to only read the rows in a ResultSet object.
Forward only : Allows you to move the result set cursor from first
row to
last row in forward direction only.
Updatable : Allows you to update the result set rows retrieved from
a database table.
boolean absolute (int i) : Shifts the control of a result set cursor to the
boolean relative (int i) : Shifts the control of a result set cursor , forward
22
Statement stmt =
con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
if (rs.isBeforeFirst()== true)
System.out.println(“Result set cursor id before first row in result
set”);
if (rs.first() == true)
System.out.println(rs.getString(1) + “,” +
rs.getString(2)+”,”+rs.getString(3));
ResultSet rs = stmt.executeQuery
(“SELECT au_id , city , state FROM authors WHERE au_id =
‘123’ ”) ;
rs.next () ;
rs.updateString(“state” , “MAHARASHTRA”) ;
rs.updateString(“city” , “Pune”);
25
PreparedStatement interface
This helps in reducing the load on the database server and thus
improving the performance of the application .
26
The PreparedStatement interface inherits the following methods
to execute SQL statement s from the Statement interface:
27
stat = con.prepareStatement(“SELECT * FROM authors WHERE au_id =
? ”) ;
1. void setByte (int index , byte val) : Sets the java byte type
value for the parameter corresponding to index passed as a
parameter.
2. void setBytes (int index , byte[] val) : Sets the Java byte
type array for the parameter corresponding to index passed as
a parameter.
4. void setDouble (int index, double val) : Sets the Java double
type value value for the parameter corresponding to the index
passed as a parameter.
29
5. void setInt (int index , int val) : Sets the Java int type value for
the parameter corresponding to index passed as a parameter.
6. void setLong(int index , long val) : Sets the Java long type
value for the parameter corresponding to index passed as a
parameter.
7. void setFloat (int index , float val) : Sets the Java float type
value for the parameter corresponding to index passed as a
parameter.
8. void setShort (int index , short val) : Sets the Java short type
value for the parameter corresponding to index passed as a
parameter.
PreparedStatement ps = con.prepareStatement(str) ;
ps.setString(1 , “101”);
31
Inserting Rows
String str =
“ INSERT INTO authors (au_id , au_fname , au_lname) VALUES
(? , ? , ? ) ” ;
PreparedStatement ps = con.prepareStatement(str);
ps.setString (3 , “XYZ”);
int rt = ps.executeUpdate() ;
32
Updating & Deleting Row
PreparedStatement ps = con.prepareStatement(str);
PreparedStatement ps = con.prepareStatement(str);
34
The database transactions can be committed in
two ways in the JDBC applications.
Implicit :
The Connection object uses the auto-commit mode to execute
the SQL statements implicitly.
The auto-commit mode specifies that each SQL statement in a
transaction is committed automatically as soon as the execution
of SQL statement completes.
By default all the transaction statement in a JDBC application are
auto-committed.
Explicit :
For explicitly committing transaction statement in a JDBC
application, you have to use the setAutoCommit () method .
This method accepts either of the two values , true or false , to
set or reset the auto-commit mode for a database. The auto-
commit mode is set to false to commit a transaction explicitly .
You can set the auto-commit mode to false using the following
35 method call : con.setAutoCommit (false) ;
When you set the auto-commit mode to false ,the operations
performed by the SQL statement are not reflected permanently in a
database.
You need to explicitly call the commit () method of the Connection
interface to reflect the changes made by the transactions in a
database.
All the SQL statement that appear between two commit() methods
are treated as a single transaction and are executed as a single unit.
The rollback () method is used to undo the changes made in the
database after the last commit operations.
36
You can call the rollback () method using the following method call :
Batch Updates
The SQL statements that are part of a batch are called the
batchable statements.
39
con.setAutoCommit (false) ;
40
Exception-Handling in Batch Updates
The batch update operations can throw two types of exceptions ,
SQLException and BatchUpdateException.
The update count for all the SQL statement that are executed
successfully is stored in the array in the same order in which the
SQL statement appear in the batch.
You can traverse the array of update count to determine the SQL
statement that is not executed successfully in a batch.
The null value in an array of update count indicates that the SQL
statement in the batch failed to execute.
42
import java.sql.*;
public class BatchUpdate
{
public static void main (String arg [])
{
try
{
/ * Batch Update Code comes here */
} catch (BatchUpdateException bexp)
{
System.err.println (“SQL Exception :” +
bexp.getMessage ()) ;
System.err.println(“Update Counts”) ;
int [] count = bexp.getUPdateCounts();
44
Creating Stored Procedures
You can use the executeUpdate () to execute the CREATE
PROCEDURE SQL statement.
Stored procedures can be of two types , parameterized and non-
parameterized.
Non – parameterized stored procedure in a JDBC application:
46
You can use the following code snippet to create a parameterized
stored procedure.
49
1. CallableStatement prepareCall (String str) : Creates a
CallableStatement object to call a stored procedure. The prepareCall
() accepts a string as a parameter that contains an SQL statement to
call a stored procedure. You can also specify the placeholders to
accept parameters in the SQL statement.
51
The syntax to call a stored procedure without parameter is :
{ call <procedure_name> } ;
ResultSet rs = cs.executeQuery() ;
while(rs.next())
{
System.out.println(“Author ID :” + rs.getString(1) + “\t”);
System.out.println(“Author First Name :” + rs.getString(2) + “\
t”);
System.out.println(“Author Last Name :” + rs.getString(3) + “\
t”);
52}
Calling a Stored Procedure with Parameters
There are two forms of the SQL escape syntax, one that contains
result parameter and one that does not.
53
The syntax to call a stored procedure with parameter is :
<CallableStatement_object>.setInt(<value>)
54
If the stored procedure contains OUT and INOUT parameters, these
parameters should be registered with corresponding JDBC types
before a call to a stored procedures is precessed.
The JDBC types determine the Java data types that are used in the get
methods while retrieving the values of the OUT and INOUT
parameters.
cs.registerOutParameter (1 . Java.sql.Types.STRING) ;
Accepts the position of the placeholder and a constant in the
java.sql.Types class as parameters.
try
{
// pass IN parameter
56
cs.setString (1 , “123-456” ) ;
//Register OUT paramter
cs.registerOutParameter(2 , Types.VARCHAR);
cs.registerOutParameter(3 , Types.VARCHAR);
cs.registerOutParameter(4 , Types.VARCHAR);
cs.registerOutParameter(5 , Types.VARCHAR);
fname = cs.getString(2) ;
lname = cs.getString(3) ;
address = cs.getString(4) ;
city = cs.getString(5) ;
----
-----
----
}
57
Using METADATA in JDBC
Metadata is the information about data , such as structure and
properties of a table.
1 . DatabaseMetaData interface
2 . ResultSetMetaData interface
58
DatabaseMetaData Interface
The DatabaseMetaData interface provides the methods that enable
you to determine the properties of a database or RDBMS.
DatabaseMetaData dm = con.getMetaData () ;
59
ResultSet getColumns (String catalog , String schema, String
tablename
String col_name)
-> Retrieves the information about a column of a database
table
that is available in the specified database catalog.
Connection getConnection ()
String getDriverName ()
60String getDriverVersion ()
ResultSet getPrimaryKeys (String catalog , String schema , String table)
-> Retrieves the information about the primary keys of the
database tables.
String getURL ()
-> Retrieves the URL of the database
boolean isReadOnly ()
-> Returns a boolean value that indicates whether the
database
is a read only database.
boolean supportsSavePoints ()
-> Returns a boolean value that indicates whether the
database
61
supports savepoints.
Using ResultMetaData Interface
62
int getColumnCount () : Returns an integer indicating the total number
of
columns in a ResultSet object .
int getColumnType (int col_index) : Retrieves the SQL data type of the
table column corresponding to the index passed as a parameter.