What Is JDBC Driver
What Is JDBC Driver
JDBC (Java Database Connectivity) is uses for connect java application with database. It is Java SE
technology, which is install automatically with the JDK software. JDBC is an API (Application
programming interface) used to communicate Java application to database in database independent
and platform independent manner. It provides classes and interfaces to connect or communicate Java
application with database.
Jdbc ia a part of JDK software so no need to install separate software for Jdbc API
java.sql package
javax.sql package
Jdbc Architecture
Jdbc API is a java API that can access any kind of tabular data and specific data stored in
relational database management system (RDBMS).
Packages
java.sql package
javax.sql package
Classes In Jdbc
DriverManager
SQLException
Types
Date
Time
Interfaces In Jdbc
Connection
Statement
PreparedStatement
CallableStatementResultset
ResultSetMetaData
DatabaseMetaData
Driver
Blob
Clob
There are 6 steps to connect any java application with the database using JDBC. They are as
follows:
In this step we load the JDBC driver class into JVM. This step is also called as registering the
JDBC driver. The forName() method of Class class is used to register the driver class. This
method is used to dynamically load the driver class. This step can be completed in two ways.
Syntax
class.forName("Sun.Jdbc.Odbc.JdbcOdbcDriver");
Syntax
Sun.Jdbc.Odbc.JdbcOdbcDriver jod=new Sun.Jdbc.Odbc.JdbcOdbcDriver();
DriverManager.registerDriver(jod);
2. Create the connection object
In this step connection between a java program and a database will be opened. To open the
connection, we call getConnection() method of DriverManager class.
For getConnection() method we need to pass three parameters.
url
username
password
url: url is used to select one register JDBC driver among multiple registered driver by
DriverManager class.
username and password: username and password are used for authentication purpose.
To transfer sql commands from java program to database we need statement object. To create a
statement object we call createStatement() method of connection interface. The
createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.
Call any one of the following three methods of Statement interface is used to execute queries to
the database and to get the output.
import java.sql.*;
class CreateTable
{
public static void main(String[] args) throws Exception
{
//step-1
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver is laoded");
//step-2
Connection
con=DriverManager.getConnection("jdbc:odbc:ramadsn","system","system");
System.out.println("connection is established");
//step-3
Statement stmt=con.createStatement();
System.out.println("statement object is cretaed");
//step-4
int i=stmt.executeUpdate("create table student(sid number(3),sname
varchar2(10),marks number(5))");
//step-5
System.out.println("Result is="+i);
System.out.println("table is created");
//step-6
stmt.close();
con .close();
}
}
What is JDBC Driver?
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to interact with it
by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with their behaviours defined
and their actual implementaions are done in third-party drivers. Third party vendors implements
the java.sql.Driver interface in their database driver.
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
This thin driver uses the following three information to connect with a database.
Because thin driver internally uses native protocol. Native protocol is a server dependent
protocol it means the protocol can establish connection with a particular server only.
url: Jdbc:Oracle:thin@ipaddress:sid
name System
password Tiger
This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.
The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.
}
catch(Exception e)
{
System.out.println(e);
}
}
}
You need to do this registration only once in your program. You can register a driver in one of
two ways.
Approach I - Class.forName()
The most common approach to register a driver is to use Java's Class.forName() method, to
dynamically load the driver's class file into memory, which automatically registers it. This
method is preferable because it allows you to make the driver registration configurable and
portable.
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Approach I - Class.forName()
The most common approach to register a driver is to use Java's Class.forName() method, to
dynamically load the driver's class file into memory, which automatically registers it. This
method is preferable because it allows you to make the driver registration configurable and
portable.
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Database URL Formulation
After you've loaded the driver, you can establish a connection using the
DriverManager.getConnection() method. For easy reference, let me list the three overloaded
DriverManager.getConnection() methods −
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to your
database.
Formulating a database URL is where most of the problems associated with establishing a
connection occurs.
Following table lists down the popular JDBC driver names and database URL.
Following table lists down the popular JDBC driver names and database URL.
In case of preparedStatement
First sql command is send to database for compilation and then compiled code will be stored in
preparedStatement object.
The compiled code will be executed for n number of time without recompiling the sql command.
The criteria to use preparedStatement is when we want to execute same sql query for multiple
times with different set of values.
Comparatively preparedStatement is faster than Statement Interface.
Difference between PreparedStatement and Statement
Syntax
Connection con; // con is reference of connection
PreparedStatement pstmt=con.prepareStatement("sql command");
To pre-compile a command only syntax of the command is required so we can use '?' symbol for
value in the command. '?' symbol is called parameter or replacement operator or place-resolution
operator.
import java.sql.*;
import javax.sql.*;//PreparedStatement;
import java.util.*;
class PrepardTest1
{
Connection con;
void openConnection()throws Exception
{
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("driver is loaded");
con=DriverManager.getConnection("jdbc:oracle:thin:@John-
pc:1521:xe","system","system");
System.out.println("connection is opend");
}
void insertTest()throws Exception
{
PreparedStatement pstmt=con.prepareStatement("insert into student
values(?,?,?) ");
Scanner s=new Scanner(System.in);
String Choice="yes";
while(Choice.equals("yes"))
{
System.out.println("enter student id");
int sid=s.nextInt();
System.out.println("enter student name");
String sname=s.next();
System.out.println("enter Student marks");
int marks=s.nextInt();
Callablestatement in Jdbc
To call the procedures and functions of a database, CallableStatement interface is used.
Syntax
CallableStatement cstmt=con.prepareCall("sql command");
Syntax
CallableStatement cstmt=con.prepareCall("{call procedure name or function
name}");
Syntax
CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
One problem though is, that Statement interface is used to execute static SQL
statements with no option to send parameters. Though you can always use a
StringBuilder to append parameters to the SQL and use it with Statement but there
is a better option provided by JDBC itself in the form of PreparedStatement which
is a sub-interface of Statement. In this post we'll see how to use
PreparedStatement in Java with examples.
You can get the PreparedStatement object by calling the prepareStatement method
of the Connection class.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
// Creating connection
connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs",
"root", "admin");
JDBCPrepStmt prep = new JDBCPrepStmt();
prep.insertEmployee(connection, "Kate", 24);
prep.updateEmployee(connection, 22, 30);
prep.displayEmployee(connection, 22);
//prep.deleteEmployee(connection, 24);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(connection != null){
//closing connection
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // if condition
}// finally
}
/**
* @param connection
* @throws SQLException
*/
private void insertEmployee(Connection connection, String name, int age)
throws SQLException{
String insertSQL = "Insert into employee (name, age) values (?, ?)";
PreparedStatement prepStmt = null;
try {
prepStmt = connection.prepareStatement(insertSQL);
prepStmt.setString(1, name);
prepStmt.setInt(2, age);
int count = prepStmt.executeUpdate();
System.out.println("Count of rows inserted " + count);
}finally{
if(prepStmt != null){
prepStmt.close();
}
}
}
/**
* @param connection
* @param id
* @param age
* @throws SQLException
*/
private void updateEmployee(Connection connection, int id, int age) throws
SQLException{
String updateSQL = "Update employee set age = ? where id = ?";
PreparedStatement prepStmt = null;
try {
prepStmt = connection.prepareStatement(updateSQL);
prepStmt.setInt(1, age);
prepStmt.setInt(2, id);
int count = prepStmt.executeUpdate();
System.out.println("Count of rows updated " + count);
}finally{
if(prepStmt != null){
prepStmt.close();
}
}
}
/**
* @param connection
* @param id
* @throws SQLException
*/
private void deleteEmployee(Connection connection, int id) throws
SQLException {
String deleteSQL = "Delete from employee where id = ?";
PreparedStatement prepStmt = null;
try {
prepStmt = connection.prepareStatement(deleteSQL);
prepStmt.setInt(1, id);
int count = prepStmt.executeUpdate();
System.out.println("Count of rows deleted " + count);
}finally{
if(prepStmt != null){
prepStmt.close();
}
}
}
/**
* @param connection
* @param id
* @throws SQLException
*/
private void displayEmployee(Connection connection, int id) throws
SQLException{
String selectSQL = "Select * from employee where id = ?";
PreparedStatement prepStmt = null;
try {
prepStmt = connection.prepareStatement(selectSQL);
prepStmt.setInt(1, id);
ResultSet rs = prepStmt.executeQuery();
while(rs.next()){
System.out.println("id : " + rs.getInt("id") + " Name : "
+ rs.getString("name") + " Age : " + rs.getInt("age"));
}
}finally{
if(prepStmt != null){
prepStmt.close();
}
}
}
Parameterized statement– In the example you can see that all the SQL
statements are parameterized and ‘?’ is used as a placeholder in
parameterized statements.
As example -
String insertSQL = "Insert into employee (name, age) values (?, ?)";
Setter methods– Values for these placeholders are provided through setter
methods. PreparedStatement has various setter methods for different data
types i.e. setInt(), setString(), setDate() etc.
As example -
String insertSQL = "Insert into employee (name, age) values (?, ?)";
For this sql where the first parameter is String (name) and second parameter
is of type int (age), you need to set the parameters on the
PreparedStatement object as follows -
prepStmt.setString(1, name);
prepStmt.setInt(2, age);
import java.sql.*;
class PreparedStatDemo
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","username", "password");
PreparedStatementps = con.prepareStatement("insert into Student values(?, ?, ?)");
ps.setInt(1, 101);
ps.setString(2, "Surendra");
ps.setString(3, "MCA");
ps.executeUpdate();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
CallableStatement Interface
The CallableStatement interface is used to execute the SQL stored procedure in a database. The JDBC
API provides stored procedures to be called in a standard way for all RDBMS.
A stored procedure works like a function or method in a class. The stored procedure makes the
performance better because these are precompiled queries.
For example:
CallableStatementcallableStatement = con.prepareCall("{call procedures(?,?)}");
// ProcedureDemo.java
import java.sql.*;
classProcedureDemo
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tiger");
CallableStatementstmt = con.prepareCall("{call insertStudents(?, ?) }");
stmt.setInt(1, 101);
stmt.setString(2, Vinod);
stmt.setString(3, BE);
stmt.execute();
System.out.println("Record inserted successfully");
con.close();
stmt.close();
}
catch(Execption e)
{
e.printStackTrace();
}
}
}
ResultSet Metadata:
java.sql.ResultSetMetaData is also one of the frequently used interface in the JDBC API. This interface
provides quick overview about a ResultSet object like number of columns, column name, data type of a
column etc. You often need this info about a ResultSet object before processing the actual data of a
ResultSet. In this post, we will discuss ResultSetMetaData in detail with some simple examples.
ResultSetMetaData In JDBC
ResultSetMetaData is an interface in java.sql package of JDBC API which is used to get the metadata
about a ResultSet object. Whenever you query the database using SELECT statement, the result will be
stored in a ResultSet object. Every ResultSet object is associated with one ResultSetMetaData object.
This object will have all the meta data about a ResultSet object like schema name, table name, number
of columns, column name, datatype of a column etc. You can get this ResultSetMetaData object using
getMetaData() method of ResultSet.
1. import java.sql.*;
2. class Rsmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. PreparedStatement ps=con.prepareStatement("select * from emp");
10. ResultSet rs=ps.executeQuery();
11. ResultSetMetaData rsmd=rs.getMetaData();
12.
13. System.out.println("Total columns: "+rsmd.getColumnCount());
14. System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
15. System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)
);
16.
17. con.close();
18. }catch(Exception e){ System.out.println(e);}
19. }
20. }
DatabaseMetaData interface provides methods to get meta data of a database such as database
product name, database product version, driver name, name of total number of tables, name of
total number of views etc.
1. import java.sql.*;
2. class Dbmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. DatabaseMetaData dbmd=con.getMetaData();
10.
11. System.out.println("Driver Name: "+dbmd.getDriverName());
12. System.out.println("Driver Version: "+dbmd.getDriverVersion());
13. System.out.println("UserName: "+dbmd.getUserName());
14. System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
15. System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());
16.
17. con.close();
18. }catch(Exception e){ System.out.println(e);}
19. }
20. }
Important Points
In Jdbc only PreparedStatement support the binary data transfer between a Java
application to database.
Jdbc supports only gif or jpeg or png type of images to insert or read from a database.
To set binary data into a parameter of PreparedStatement object, you need to call
setBinaryStream().
Parameters of setBinaryStream()
parameter index
fileInputStream object
Size of the file
Example
File f=new File("c:/img001.gif");
int size=(int)f.length();
Note: In Java forward slash (/) is allowed but backward slash (\) is not allowed at the time of
writing of path.
import java.sql.*;
import java.util.*;
import java.io.*;
class PhotoInsert
{
Connection con;
public void openCon()throws Exception
{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@rama-
pc:1521:xe","system","system");
System.out.println("connection is opened");
}
public void insert()throws Exception
{
Scanner s=new Scanner(System.in);
PreparedStatement pstmt=con.prepareStatement("insert into emp_info
values(?,?,?)");
System.out.println("enter emp id");
int empid=s.nextInt();
pstmt.setInt(1,empid);
System.out.println("enter emp name");
String empname=s.next();
pstmt.setString(2,empname);
System.out.println("enter photo file path");
String path=s.next();
Important Points
Again we need to convert binary data to image, because in database binary data of image
is store.
When we select image from database, it will be store in a ResultSet object..
From ResultSet object we need to read the binary data and we need to store in a
InputStream object.
import java.sql.*;
import java.util.*;
import java.io.*;
class PhotoSelect
{
Connection con;
public void openCon()throws Exception
{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@rama-
pc:1521:xe","system","system");
System.out.println("connection is opened");
}
public void select()throws Exception
{
Scanner s=new Scanner(System.in);
PreparedStatement pstmt=con.prepareStatement("select photo from emp_info
where empid=?");
System.out.println("enter emp id");
int empid=s.nextInt();
pstmt.setInt(1,empid);
ResultSet rs=pstmt.executeQuery();
rs.next();
InputStream is=rs.getBinaryStream(1);
rs.close();
FileOutputStream fos=new FileOutputStream("c:/img001.gif");
int k;
while((k=is.read())!=-1)
{
fos.write(k);
}
System.out.println("picture is ready open c:drive");
pstmt.close();
fos.close();
}//end of
public void closeCon()throws Exception
{
con.close();
}//end of select