JDBC
JDBC
JDBC, along with the database driver, can access databases and
spreadsheets.
1. JDBC API: It provides various methods and interfaces for easy communication
with the database. It provides two packages as follows, which contain the java SE
and Java EE platforms to exhibit WORA(write once run anywhere) capabilities.
1. java.sql.* 2. javax.sql.*
Three-tier model: the user’s queries are sent to middle-tier services, from which the
commands are again sent to the data source. The results are sent back to the middle tier,
and from there to the user.
This type of model is found very useful by management information system directors.
Type-1 Driver: JDBCD-ODBC Bridge Driver
Acts as bridge between JDBC and other database connectivity mechanism like ODBC.
Example: Sun JDBC-ODBC bridge driver(in sun.jdbc.odbc package)
Converts JDBC calls into ODBC calls and redirects the request to ODBC driver
ODBC driver uses SP(Stored Procedure) APIs to make DBMS specific call
Advantages
Single driver implementation for different databases
Vendor independent driver
Supports all databases supported by the ODBC driver
Disadvantages
Slow execution speed due to large number of calls and translations
Fully dependent on ODBC driver
ODBC client library should be installed at client machine
Type-2 Driver: Java to Native API(Partly Java Driver)
Type-2 Driver converts JDBC calls into database vendor specific native call using JNI
These database specific calls then dispatched to db specific native libraries
Native libraries sends request to db server by native protocol
Example: Weblogic Type-2 Driver by BEA Weblogic
Advantages
Fast processing as compared to Type-1 Driver
Contains exclusive feature provided by DB vendor and supported by JDBC specification
Disadvantages
Native librariesto be installed on client machine
Executes DB specific native functions on JVM, bug in Type-2 driver might crash JVM
Increase the cost of application in case it runs on different platforms
Type-3 Driver: Java to Network Protocol(Pure Java Driver)
Type-3 Driver converts JDBC calls into middleware server specific calls
Driver communicates with middleware over a socket
Middleware converts these calls into database specific calls
These type of drivers also known as net-protocol drivers
Example: IDS Driver, WebLogic RMI Driver
Advantages
Additional features like Pool Management, performance improvement and connection availability and auto
downloadable
No native library needed to be installed in client machine
Database independent, middleware takes care of converting calls to DB specific calls
Database details are not required at client side because it is available at middleware server
Easy to switch among databases, without changing client side driver classes
Disadvantages
Performes task slowly because network call is involved
Cost of middleware server is more
Type-4 Driver: Java to Database Protocol(Pure Java Driver)
• Implements the database protocol to interact directly with a database
• prepares a DBMS specific network message & communicates with DB server -socket
• Type-4 Driver uses DB specific proprietary protocol for communication
• Generally,are implemented by DBMS vendors, since the protocols used are proprietary
• Example: Oracle Thin driver, WebLogic & Mysqlserver4 for MY SQL server
Advantages
This is lightweight driver
Auto downloadable
No native library needed to be installed at client side
No middleware server required
Disadvantages
This uses database specific proprietary protocol so it is vendor dependent
Essentials of JDBC Program
import java.sql.*; // Import Package
ORACLE oracle.jdbc.driver.OracleDriver
DB2 COM.ibm.db2.jdbc.net.DB2Driver
Sybase com.sybase.jdbc.SybDriver
Interfaces of JDBC API
• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface
• Classes of JDBC API
PreparedStatement • Use this when you plan to use the SQL statements many times.
• The PreparedStatement interface accepts input parameters at
runtime.
CallableStatement • Use this when you want to access the database stored procedures.
• The CallableStatement interface can also accept runtime input
parameters.
Statement Interface
• Represents object that is used for executing a static SQL statement and returning the
results it produces.
• SQL Statements without parameters are normally executed using Statement Objects.
• In case if same SQL statement is executed many times, it may be more efficient to use
PreparedStatement object.
• ResultSet object is returned as result which static SQL statement produces while
execution.
• By default, only one ResultSet object per Statement object can be open at the same
time.
• All execution methods in the Statement interface implicitly close a current ResultSet
object of the statement if an open one exists.
import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; // JDBC driver name
and database URL
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username"; // Database
credentials
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver"); //STEP 2: Register JDBC driver
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS); //STEP 3: Open a
connection
System.out.println("Connected database successfully...");
System.out.println("Inserting records into the table...");
stmt = conn.createStatement(); //STEP 4: Create statement and
Execute query
String sql = "INSERT INTO Registration " + "VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES (101, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} //end main
} //end JDBCExample
Execution control of statement
PreparedStatement Interface
• An object that represents precompiled SQL statement
• This object can then be used to efficiently execute this statement multiple times
• The setter methods (setShort, setString, and so on) for setting IN parameter values must
specify types that are compatible with the defined SQL type of the input parameter.
• For instance, if the IN parameter has SQL type INTEGER, then the method setInt should
be used.
ps.setInt(1,eno);
ps.setString(2,ename);
ps.setDouble(3,sal);
ps.setInt(4,dno);
ps.executeUpdate();
System.out.println("Want to add more? ");
}while(dis.readLine().equalsIgnoreCase("y"));
con.close();
}
}
ResultSet interface
Represents table of data, usually generated by executing a statement that queries database.
• ResultSet interface provides getter methods(like getString, getInt, and so on) to retrieve
column value from the current row
• Values can be retrieved using either the index number of the column or the name of the
column
• In general using column number will be more efficient, it starts from 1 not 0
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected
database...");
Connection conn = DriverManager.getConnection(DB_URL, USER,
PASS);
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
String sql = "SELECT id, first, last, age FROM
Registration";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last); }
rs.close();
} }
Example for Resultset object using prepared statement
import java.sql.*;
import java.io.*;
public class PreparedStatementExSelect{
public static void main(String[] args)throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","system","manager");
String sql = "SELECT * FROM emp WHERE empno=?";
PreparedStatement ps = con.prepareStatement(sql);
DataInputStream dis = new DataInputStream(System.in);
do{
System.out.print("EmpNo: ");
int eno = Integer.parseInt(dis.readLine());
ps.setInt(1,eno);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getDouble(3)+"\t"+rs.getInt(4));
}
else{
System.out.println("Employee Not Found!");
}
System.out.println("Want to find one more? ");
}while(dis.readLine().equalsIgnoreCase("y"));
con.close();
} }
Execute the query
Once you've created a Statement object, you can then use it to execute an SQL statement
with one of its three execute methods.
2. int executeUpdate (String SQL): Returns the number of rows affected by the
execution of the SQL statement. Use this method to execute SQL statements for
which you expect to get a number of rows affected - for example, an INSERT,
UPDATE, or DELETE statement.
Statement PreparedStatement
1. Single object can execute multiple 1. Only one SQL
SQL
2. Every execution of SQL needs 2. Only one compilation for multiple
compilation execution of SQL
3. Difficult to include multiple 3. Easy writing SQL because of
concatanation positional parameters
4. Needs DB specific format 4. Easy working with compiler types
The executeBatch() is used to start the execution of all the statements grouped
together.
The executeBatch() returns an array of integers, and each element of the array
represents the update count for the respective update statement.
Just as you can add statements to a batch for processing, you can remove them
with the clearBatch() method.
This method removes all the statements you added with the addBatch() method.
However, you cannot selectively choose which statement to remove.