Module4 JDBC PDF
Module4 JDBC PDF
Chapter -1
JDBC
1.1 Introduction (Talking to JDBC):
1 | 29
Module-4 JDBC
1. JDBC-ODBC bridge driver:
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver
converts JDBC method calls into the ODBC function calls.
The driver is a platform dependent because it
uses ODBC which is depends on native
libraries of the operating system and also the
driver needs other installation.
Example: ODBC must be installed on the
computer and the database must support
ODBC driver.
Type-1 is the simplest compare to all other
driver but it’s a platform specific i.e. only on
Microsoft platform. The JDBC-ODBC
Bridge is use only when there is no PURE-
JAVA driver available for a particular
database.
Advantages:
easy to use as compare the all other driver.
can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC function calls.
The ODBC driver needs to be installed on the client machine.
Not suitable for applets because the ODBC driver needs to be installed on the client machine.
2. Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into
native calls of the database API. It is not written entirely in java.
Advantage:
There is no implantation of JDBC-ODBC
Bridge so it’s faster than a type-1 driver
Performance upgraded than JDBC-ODBC
bridge driver.
Disadvantage:
The Native driver needs to be installed on
the each client machine.
The Vendor client library needs to be
installed on client machine.
Not all databases have the client side
library.
This driver supports all JAVA applications
except applets.
2 | 29
Module-4 JDBC
3. Network Protocol Driver:
The Network Protocol driver uses
middleware (application server) that
converts JDBC calls directly or
indirectly into the vendor-specific
database protocol and the same
driver can be used for multiple
databases. It is fully written in java.
Advantage:
No client side library is required
because the middleware is
database independent and it
communicates with client.
Type-3 driver can be used in any web application as well as on internet also because there is no any software
require at client side.
A single driver can handle any database at client side so there is no need a separate driver for each database.
The middleware server can also provide the typical services such as connections, auditing, load balancing,
logging etc.
Disadvantages:
Network support is required on client machine.
Requires database-specific coding to be done in the middle tier, may be increase complexity.
Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be
done in the middle tier.
4. Thin driver:
The thin driver converts JDBC calls
directly into the vendor-specific
database protocol and in between do
not need to be converted any other
formatted system so this is the fastest
way to communicate quires with the
DBMS. It is fully written in Java
language.
Advantage:
It is a 100% pure JAVA Driver
so it’s a platform independence
No translation or middleware layers are used so consider as a better performance than all other drivers.
No software is required at client side or server side.
The all process of the application-to-database connection can manage by JVM so the debugging is also
managed easily.
3 | 29
Module-4 JDBC
Disadvantage:
Drivers depends on the Database as different database vendors use different network protocols.
There is a separate driver needed for each database at the client side.
Example: Class.forName("com.mysql.jdbc.Driver");
iii. Open a Connection:
To establish the connection with any database follow the below two step:
a. Define Connection URL: In JDBC, a connection URL specifies the server host, port, and database
name with which to establish a connection.
Syntax: Connection object_name; Example: Connection con;
b. Establish the connection: With the connection URL, username, and password, a network
connection to the database can be established. Once the connection is established, database queries can
be performed until the connection is closed.
Syntax: public static Connection getConnection(String url)
throws SQLException
public static Connection getConnection(String url,
String name, String password) throws SQLException
4 | 29
Module-4 JDBC
The Connection class instance includes other useful methods to create reference for different statements,
which briefly describe below.
Methods Description
createStatement Create Statement object without any parameter to the database.
prepareStatement Creates precompiled queries for submission to the database.
prepareCall Accesses stored procedures in the database
rollback/commit Controls transaction management.
close Terminates the open connection.
isClosed Determines whether the connection timed out or was explicitly closed.
Interfaces Description
For executing a simple SQL statement that means the Statement object is used to execute
simple or static queries. It is created using createStatement( ) method in Connection class.
Statement
6 | 29
Module-4 JDBC
Commonly the following methods are used to execute the statements:
SN Methods Description
is used to execute SELECT query. It returns the object
1 public ResultSet executeQuery(String sql) of ResultSet. The ResultSet may be empty, but never
null.
Example: ResultSet results = statement.executeQuery("SELECT a, b FROM table");
is used to execute specified query, it may be create,
2 public int executeUpdate(String sql) drop, insert, update, delete etc. Returns the number of
rows affected, which could be zero.
Example: int rows = statement.executeUpdate("DELETE FROM table WHERE id=xxx“);
is used to execute queries that may return multiple
3 public boolean execute(String sql) results. Returns a boolean value of true if a ResultSet
object can be retrieved; otherwise, it returns false.
Example: boolean result= statement.execute(“SELECT column_name from table");
is used to executes a group of commands as a unit,
4 public int[] executeBatch() returning an array with the update counts for each
command.
try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, username, password);
System.out.println("Connection successfully established");
con.close();
System.out.println("Connection terminated !");
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}
7 | 29
Module-4 JDBC
Example-2: After establish the connection, INSERT records to the database using executeUpdate method with
the Statement object.
MySQLInsert.java
package StatementDemo;
import java.sql.*;
8 | 29
Module-4 JDBC
Example-3: After established the connection, SELECT records to the database using executeQuery method with
the Statement object.
MySQLSelect.java
package StatementDemo;
import java.sql.*;
public class MySQLSelect {
public static void main(String args[]) throws SQLException{
String url ="jdbc:mysql://localhost:3309/employeedb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;
try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, "root", "rnsit");
Statement statement = con.createStatement();
String query= "select * from empinfo";
ResultSet res = statement.executeQuery(query);
while(res.next()){
System.out.println("Employee-id :" + res.getString("eid")
+ "Employee Name :" + res.getString("ename"));
}
con.close();
System.out.println("Connection Terminated");
} catch(Exception e){
System.out.println("Connection failed !! "+e);
}
}
}
Example-4: After established the connection, UPDATE records to the database using executeUpdate method with
the Statement object.
MySQLUpdate.java
package StatementDemo;
import java.sql.*;
public class MySQLUpdate {
public static void main(String args[]) throws SQLException {
String url ="jdbc:mysql://localhost:3309/employeedb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;
9 | 29
Module-4 JDBC
MySQLUpdate.java (Continued)
try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, "root", "rnsit");
Before update
eid =105 After Updated Record
Example-5: After established the connection, DELETE records to the database using executeUpdate method with
the Statement object
MySQLDelete.java
package StatementDemo;
import java.io.IOException;
import java.sql.*;
import java.util.Scanner;
public class MySQLDelete {
public static void main(String args[])throws IOException {
String username ="root";
String password ="rnsit";
String url ="jdbc:mysql://localhost:3309/employeedb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;
10 | 29
Module-4 JDBC
MySQLDelete.java(Continued)
try{
Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, username, password);
Scanner sc = new Scanner(System.in);
System.out.println("Please enter employee id to delete: ");
int eid = sc.nextInt();
Statement statement = con.createStatement();
String query= "delete from empinfo where eid="+eid+"";
int rs = statement.executeUpdate(query);
if(rs==1){
System.out.println("Record Deleted");
con.close();
}
else{
System.out.println("no such record");
con.close();
}
System.out.println("Connection Terminated");
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}
11 | 29
Module-4 JDBC
Example-6: To establish the connection to MySQL.
MyConnection.java
package MyDatabase;
import java.sql.*;
public class MyConnection {
public static void main(String args[]){
String username ="root";
String password ="rnsit";
String url ="jdbc:mysql://localhost:3309/studentdb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;
try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, username, password);
System.out.println("Connection successfully established");
con.close();
System.out.println("Connection terminated !");
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}
Example-7: After establish the connection, INSERT records to the database using executeUpdate method with
the PreparedStatement object.
MysqlInsert.java
package myDatabase;
import java.sql.*;
public class MysqlInsert {
public static void main(String args[]){
String url ="jdbc:mysql://localhost:3309/studentdb";
String driver= "com.mysql.jdbc.Driver";
String sname="Anusha", usn="1RN13MCA07", Pass="True";
Connection con =null;
try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, “root”, “rnsit”);
System.out.println("Connection successfully established");
12 | 29
Module-4 JDBC
MysqlInsert.java(Continued)
PreparedStatement pre = con.prepareStatement("insert into
studinfo(usn, sname, pass) values(?,?,?)");
pre.setString(1,usn);
pre.setString(2,sname);
pre.setString(3,Pass);
int rs = pre.executeUpdate();
if(rs==1){
System.out.println("RECORD Inserted");
con.close();
}
else {
System.out.println("Insertion FAILED");
con.close();
}
System.out.println("Connection terminated !");
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}
Example-8: After established the connection, SELECT records to the database using executeQuery method with
the PreparedStatement object.
MysqlSelect.java
package MyDatabase;
import java.sql.*;
public class MysqlSelect {
public static void main(String args[]) throws SQLException {
String url ="jdbc:mysql://localhost:3309/studentdb";
try{
Class.forName("com.mysql.jdbc.Driver";).newInstance();
Connection con=DriverManager.getConnection(url,"root","rnsit");
PreparedStatement pre = con.prepareStatement("select * from studinfo");
ResultSet res = pre.executeQuery();
while(res.next()){
System.out.println("Name :" + res.getString("sname")+" USN:"
+ res.getString("usn") +" Result:" + res.getString("pass"));
}
con.close();
}catch(Exception e){
System.out.println(e);
}
}
}
13 | 29
Module-4 JDBC
Example-9: After established the connection, UPDATE records to the database using executeUpdate method with
the PreparedStatement object.
MySqlUpdate.java
package MyDatabase;
import java.sql.*;
14 | 29
Module-4 JDBC
Example-10: After established the connection, DELETE records to the database using executeUpdate method
with the PreparedStatement object.
MysqlDelete.java
package MyDatabase;
import java.io.IOException;
import java.sql.*;
import java.util.Scanner;
public class MysqlDelete {
public static void main(String args[])throws IOException {
String url ="jdbc:mysql://localhost:3309/studentdb";
String driver2= "com.mysql.jdbc.Driver";
String usn;
Connection con =null;
try{
Class.forName(driver2).newInstance();
con=DriverManager.getConnection(url, “root”, “rnsit”);
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the usn to delete : ");
usn = sc.next();
PreparedStatement pre = con.prepareStatement("delete from studinfo where usn=?");
pre.setString(1,usn);
int rs = pre.executeUpdate();
if(rs==1){
System.out.println("Record Deleted");
con.close();
}
else{
System.out.println("no such record");
con.close();
}
} catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}
15 | 29
Module-4 JDBC
1.5 JDBC in Action ResultSets:
The ResultSet object contains the data returned by the database. executeQuery() method returns the ResultSet
object that contains the data was requested by the query for further processing.
Data in a ResultSet object is logically organized into a virtual table consisting of rows and columns. In addition
to data, it also contains metadata such as column name, column type etc.
The ResultSet uses a virtual cursor to point to a row of a virtual table. The virtual cursor is positioned above the
first row of the data when the ResultSet is returned by the executeQuery( ) method. So virtual cursor must be
moved to first row using next( ) method.
The next( ) method returns a Boolean true if row contains the data, otherwise, a Boolean value false is returned
indicating that no more rows exists in the ResultSet. Once the virtual cursor points to arrow, the getXXX( )
method is used to copy data from the row to variable.
Note: A J2EE component must move the virtual cursor to each row and the other methods of ResultSet object to
interact with the data stored in columns in that row.
The following are the ResultSet methods can use to process the result.
Methods Description
next/previous Moves the cursor to the next or previous row in the ResultSet, respectively
The relative method moves the cursor a relative number of rows, either positive (up) or
relative / negative (down).
absolute The absolute method moves the cursor to the given row number. If the absolute value is
negative, the cursor is positioned relative to the end of the ResultSet.
Returns the value from the column specified by the column name or column index as an
getXxx()
Xxx Java Can return 0 or null if the value is an SQL NULL.
Checks whether the last getXxx read was an SQL NULL. This check is important if the
column type is a primitive (int, float etc.) and the value in the database is 0. A zero value
wasNull would be indistinguishable from a database value of NULL, which is returned as a 0. If
the column type is an object (String, Date, etc.), you can simply compare the return value
to null
findColumn Returns the index in the ResultSet corresponding to the specified column name.
getRow Returns the current row number, with the first row starting at 1
Returns a ResultSetMetaData object describing the ResultSet. ResultSetMetaData gives
getMetaData
the number of columns and the column names.
getColumnCount, getColumnName., isReadOnly. getColumnType. isSearchable, isNullable.
16 | 29
Module-4 JDBC
Example-11: After established the connection, INSERT more than one records to the database using
executeBatch method with the Statement object.
17 | 29
Module-4 JDBC
Example-12: After established the connection, INSERT more than one records to the database using
executeBatch method with the PreparedStatement object.
Before inserting
After inserted
18 | 29
Module-4 JDBC
1.7 Callable Statement Interface:
To call the stored procedures and functions, CallableStatement interface is used. It also creates the
CallableStatement object, which would be used to execute a call to a database stored procedure.
Three types of parameters exist: IN, OUT, and INOUT.
The PreparedStatement object only uses the IN parameter.
The CallableStatement object can use all the three.
Here are the definition of parameter:
Parameter Description
A parameter whose value is unknown when the SQL statement is created.
IN
You bind values to IN parameters with the setXXX() methods.
A parameter whose value is supplied by the SQL statement it returns.
OUT
You retrieve values from the OUT parameters with the getXXX() methods.
A parameter that provides both input and output values.
INOUT You bind variables with the setXXX() methods and retrieve values with the getXXX()
methods.
If you want to use CallableStatement in java application to interact with databases, then you need to create stored
procedures; to create and call the procedure follow the below steps:
Creating Stored Procedure:
To create stored procedure for MYSQL as follow below:
Where, procedure_name – Stored
DELIMITER $$
procedure name given by user.
CREATE PROCEDURE procedure_name(Parameters List)
BEGIN Parameters List – need to list each
SQL queries and Statements; parameter and the data type separated by a
END $$ comma
Let us write stored procedure for MySQL, to find a record of CUSTOMER database:-
Example:
DELIMITER $$
CREATE PROCEDURE FindCustomerBYID_SP (IN CustomerID INT)
BEGIN
SELECT * FROM Customer WHERE id=CustomerID;
END $$
Call Procedures:
To call the stored procedures use keyword “call” and end with semicolon.
Syntax: call procedure_name(parameterlist) ;
Example: call FindCustomerBYID_SP(101) ;
The above example retrieve the data of id=’101’ details from the faculty database by calling procedure
statement FindCustomerBYID_SP by using keyword ‘call’.
19 | 29
Module-4 JDBC
Once you know about creating stored procedure and calling procedure, now you can call created stored
procedure in java application by creating CallableStatement Object.
When you used CallableStatement object, the prepareCall() method have to use to call stored procedures that
as shown below:
Syntax: public CallableStatement prepareCall("{ call procedurename(?,?. . .?)}");
2. Java Program: to retrieve all the customer details from customer table which is in the faculty
database
CallStateDemo.java
package ProcedureStatement;
import java.sql.*;
public class CallStateDemo {
public static void main(String[] args) {
Connection conn = null; CallableStatement stmt = null;
Strin url= "jdbc:mysql://localhost:3309/faculty"
try{ Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn= DriverManager.getConnection( url, "root","rnsit");
//Create a Callable Statement
stmt = conn.prepareCall("{call FindCustomerBYID_SP5(?,?)}");
stmt.registerOutParameter(1, java.sql.Types.INTEGER);
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
//Execute a stored procedure
ResultSet rs=stmt.executeQuery();
20 | 29
Module-4 JDBC
CallStateDemo.java(Continued)
//Process the result
while(rs.next()){
System.out.println("Customer ID: " + rs.getString("id"));
System.out.println("Customer Name: " + rs.getString("ename"));
}
}
catch(SQLException | ClassNotFoundException se){ }
finally{
System.out.println("Goodbye!");
stmt.close();
conn.close();
}
}
}
Example-14: After established the connection, INSERT records to the database using executeUpdate method
with the CallableStatement object.
21 | 29
Module-4 JDBC
CallStateDemoInsert.java(Continued)
//Execute a stored procedure
int rs=stmt.executeUpdate();
if(rs==1)
System.out.println("Inserted Successfully ");
else
System.out.println("Fail to Insert record");
}
catch(SQLException | ClassNotFoundException se){
}
finally{
System.out.println("Goodbye!");
stmt.close(); conn.close();
}
}
}
22 | 29
Module-4 JDBC
setXX / getXX/
SQL JDBC/Java Description
updateXX
setBoolean ()
represents a single bit value that can be zero or
BIT boolean getBoolean()
one.
updateBoolean()
setBigDecimal()
NUMERIC java.math.
getBigDecimal() Exact numerical (Same as DECIMAL)
DECIMAL BigDecimal
updateBigDecimal()
setByte () getByte() represents an 8-bit unsigned integer value
TINYINT byte
updateByte() between 0 and 255.
setShort() getShort() represents a 16-bit signed integer value between -
SMALLINT Short
updateShort() 32768 and 32767.
setInt() getInt() represents a a 32-bit signed integer value between
INTEGER Int
updateInt() - 2147483648 and 2147483647.
represents a 64-bit signed integer value between
setLong() getLong()
BIGINT Long -9223372036854775808 and
updateLong
9223372036854775807.
REAL setFloat() getFloat() REAL - a "single precision", 7 digits of mantissa.
Float
FLOAT updateFloat() FLOAT-"double precision", 15 digits of mantissa.
setDouble()
represents a "double precision" floating point
DOUBLE Double getDouble()
number which supports 15 digits of mantissa.
updateDouble()
setDate() getDate() 'YYYY-MM-DD’ format, supported range is
DATE java.sql.Date
updateDate() '1000-01-01' to '9999-12-31'.
'HH:MM:SS[millisecond]' format, range is
setTime() getTime ()
TIME java.sql.Time ‘-838:59:59.000000’ to ‘838:59:59.000000’
updateTime()
Millisecond represents in fractional value.
setTimestamp() 'YYYY-MM-DD 'HH:MM:SS[millisecond]'
TIMESTAMP java.sql.Timestamp getTimestamp() format, range is '1970-01-01 00:00:01.000000'
updateTimestamp() UTC to '2038-01-19 03:14:07.999999'
Stands for “Character Large Object”
setClob() getClob() is a data type that can be used to store a large
CLOB * java.sql.Clob
updateClob() amounts of character data in a database table
such as a plain text file
Stands for “Binary Large Object”
are used to store large amounts of binary data
setBlob() getBlob() in a database table, such as images, video,
BLOB* java.sql.Blob
updateBlob() png, mp3, mp4 or other types of files.
The sorts and comparisons on the stored data
are case sensitive on BLOBs
Module-4 JDBC
setXX / getXX/
SQL JDBC/Java Description
updateXX
composite data value that consists of zero or more
setARRAY() elements of a specified data type
ARRAY* java.sql.Array getARRAY() Syntax:
updateARRAY()
data_type ARRAY[int] | VARARRAY[int]
setRef() getRef () Pointer that persistently denotes an instance of a
REF * java.sql.Ref
updateRef() structured type that resides in the database
SetStruct()
Container of ordered fields each with a type
STRUCT* java.sql.Struct getStruct()
(required) and field name (optional)
updateStruct()
Note: * indicate SQL3 data type supported in JDBC 2.