Java JDBC Tutorial
Java JDBC Tutorial
Java JDBC Tutorial
Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc
drivers to connect with the database.
Before JDBC, ODBC API was the database API to connect and execute query with the database.
But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers
(written in Java language).
Do You Know
o How to connect Java application with Oracle and Mysql database using JDBC?
o What is the difference between Statement and PreparedStatement interface?
o How to print total numbers of tables and views of a database using JDBC ?
o How to store and retrieve images from Oracle database using JDBC?
o How to store and retrieve files from Oracle database using JDBC?
What is API
API (Application programming interface) is a document that contains description of all the
features of a product or software. It represents classes and interfaces that software programs can
follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc
JDBC Driver
1. JDBC Drivers
1. JDBC-ODBC bridge driver
2. Native-API driver
3. Network Protocol driver
4. Thin driver
JDBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java 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. This is now
discouraged because of thin driver.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
o 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:
Disadvantage:
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:
Disadvantage:
There are 5 steps to connect any java application with the database in java using JDBC. They
are as follows:
o Register the driver class
o Creating connection
o Creating statement
o Executing queries
o Closing connection
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
1. public static void forName(String className)throws ClassNotFoundException
1. Class.forName("oracle.jdbc.driver.OracleDriver");
The getConnection() method of DriverManager class is used to establish connection with the
database.
1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
1. public Statement createStatement()throws SQLException
1. Statement stmt=con.createStatement();
The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
1. public ResultSet executeQuery(String sql)throws SQLException
1. ResultSet rs=stmt.executeQuery("select * from emp");
2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
1. public void close()throws SQLException
1. con.close();
Example to connect to the Oracle database in java
For connecting java application with the oracle database, you need to follow 5 steps to perform
database connectivity. In this example we are using Oracle10g as the database. So we need to
know following information for the oracle database:
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database,
thin is the driver, localhost is the server name on which oracle is running, we may also
use IP address, 1521 is the port number and XE is the Oracle service name. You may
get all these information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: Password is given by the user at the time of installing the oracle database.
In this example, system is the username and oracle is the password of the Oracle database.
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7.
8. //step2 create the connection object
9. Connection con=DriverManager.getConnection(
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=con.createStatement();
14.
15. //step4 execute query
16. ResultSet rs=stmt.executeQuery("select * from emp");
17. while(rs.next())
18. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
19.
20. //step5 close the connection object
21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }
download this example
The above example will fetch all the records of emp table.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
Firstly, search the ojdbc14.jar file then open command prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
For connecting java application with the mysql database, you need to follow 5 steps to perform
database connectivity.
In this example we are using MySql as the database. So we need to know following informations
for the mysql database:
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
In this example, sonoo is the database name, root is the username and password.
1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=con.createStatement();
10. ResultSet rs=stmt.executeQuery("select * from emp");
11. while(rs.next())
12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }
16. }
download this example
The above example will fetch all the records of emp table.
To connect java application with the mysql database mysqlconnector.jar file is required to be
loaded.
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to connect java application with the access database.
Java is mostly used with Oracle, mysql, or DB2 database. So you can learn this topic only for
knowledge.
Example to Connect Java Application with access without DSN
In this example, we are going to connect the java program with the access database. In such case,
we have created the login table in the access database. There is only one column in the table
named name. Let's get all the name of the login table.
1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String database="student.mdb";//Here database exists in the current directory
6.
7. String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};
8. DBQ=" + database + ";DriverID=22;READONLY=true";
9.
10. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
11. Connection c=DriverManager.getConnection(url);
12. Statement st=c.createStatement();
13. ResultSet rs=st.executeQuery("select * from login");
14.
15. while(rs.next()){
16. System.out.println(rs.getString(1));
17. }
18.
19. }catch(Exception ee){System.out.println(ee);}
20.
21. }}
download this example
Connectivity with type1 driver is not considered good. To connect java application with type1
driver, create DSN first, here we are assuming your dsn name is mydsn.
1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String url="jdbc:odbc:mydsn";
6. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
7. Connection c=DriverManager.getConnection(url);
8. Statement st=c.createStatement();
9. ResultSet rs=st.executeQuery("select * from login");
10.
11. while(rs.next()){
12. System.out.println(rs.getString(1));
13. }
14.
15. }catch(Exception ee){System.out.println(ee);}
16.
17. }}
18. DriverManager class
19. The DriverManager class acts as an interface between user and drivers. It keeps track of
the drivers that are available and handles establishing a connection between a database
and the appropriate driver. The DriverManager class maintains a list of Driver classes
that have registered themselves by calling the method DriverManager.registerDriver().
20. Useful methods of DriverManager class
Method Description
A Connection is the session between java application and database. The Connection interface is a
factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be
used to get the object of Statement and DatabaseMetaData. The Connection interface provide
many methods for transaction management like commit(), rollback() etc.
3) public void setAutoCommit(boolean status): is used to set the commit status.By default it
is true.
4) public void commit(): saves the changes made since the previous commit/rollback
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Statement interface
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Let’s see the simple example of Statement interface to insert, update and delete the record.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system",
"oracle");
6. Statement stmt=con.createStatement();
7.
8. //stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
9. //int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 where id=33");
10. int result=stmt.executeUpdate("delete from emp765 where id=33");
11. System.out.println(result+" records affected");
12. con.close();
13. }}
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);
1) public boolean next(): is used to move the cursor to the one row next
from the current position.
2) public boolean previous(): is used to move the cursor to the one row previous
from the current position.
3) public boolean first(): is used to move the cursor to the first row in result
set object.
4) public boolean last(): is used to move the cursor to the last row in result
set object.
5) public boolean absolute(int is used to move the cursor to the specified row
row): number in the ResultSet object.
6) public boolean relative(int is used to move the cursor to the relative row
row): number in the ResultSet object, it may be positive
or negative.
Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system",
"oracle");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONC
UR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
9.
10. //getting the record of 3rd row
11. rs.absolute(3);
12. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
13.
14. con.close();
15. }}
PreparedStatement interface
1. String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
1. public PreparedStatement prepareStatement(String query)throws SQLException{}
Method Description
public void setInt(int paramIndex, int sets the integer value to the given parameter
value) index.
public void setString(int paramIndex, sets the String value to the given parameter
String value) index.
public void setFloat(int paramIndex, sets the float value to the given parameter
float value) index.
public void setDouble(int sets the double value to the given parameter
paramIndex, double value) index.
public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.
1. create table emp(id number(10),name varchar2(50));
1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system",
"oracle");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10. stmt.setInt(1,101);//1 specifies the first parameter in the query
11. stmt.setString(2,"Ratan");
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+" records inserted");
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }
download this example
1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");
2. stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name
3. stmt.setInt(2,101);
4.
5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");
download this example
Example of PreparedStatement interface that deletes the record
1. PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
2. stmt.setInt(1,101);
3.
4. int i=stmt.executeUpdate();
5. System.out.println(i+" records deleted");
download this example
1. PreparedStatement stmt=con.prepareStatement("select * from emp");
2. ResultSet rs=stmt.executeQuery();
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }
download this example
1. import java.sql.*;
2. import java.io.*;
3. class RS{
4. public static void main(String args[])throws Exception{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system",
"oracle");
7.
8. PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");
9.
10. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
11.
12. do{
13. System.out.println("enter id:");
14. int id=Integer.parseInt(br.readLine());
15. System.out.println("enter name:");
16. String name=br.readLine();
17. System.out.println("enter salary:");
18. float salary=Float.parseFloat(br.readLine());
19.
20. ps.setInt(1,id);
21. ps.setString(2,name);
22. ps.setFloat(3,salary);
23. int i=ps.executeUpdate();
24. System.out.println(i+" records affected");
25.
26. System.out.println("Do you want to continue: y/n");
27. String s=br.readLine();
28. if(s.startsWith("n")){
29. break;
30. }
31. }while(true);
32.
33. con.close();
34. }}
35. Java ResultSetMetaData Interface
36. The metadata means data about data i.e. we can get further information from the data.
37. If you have to get metadata of a table like total number of column, column name, column
type etc. , ResultSetMetaData interface is useful because it provides methods to get
metadata from the ResultSet object.
38. Commonly used methods of ResultSetMetaData interface
Method Description
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. }
Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER
Java DatabaseMetaData interface
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. public DatabaseMetaData getMetaData()throws SQLException
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. }
Output:Driver Name: Oracle JDBC Driver
Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production
download this example
1. import java.sql.*;
2. class Dbmd2{
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.
10. DatabaseMetaData dbmd=con.getMetaData();
11. String table[]={"TABLE"};
12. ResultSet rs=dbmd.getTables(null,null,null,table);
13.
14. while(rs.next()){
15. System.out.println(rs.getString(3));
16. }
17.
18. con.close();
19.
20. }catch(Exception e){ System.out.println(e);}
21.
22. }
23. }
download this example
1. import java.sql.*;
2. class Dbmd3{
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.
10. DatabaseMetaData dbmd=con.getMetaData();
11. String table[]={"VIEW"};
12. ResultSet rs=dbmd.getTables(null,null,null,table);
13.
14. while(rs.next()){
15. System.out.println(rs.getString(3));
16. }
17.
18. con.close();
19.
20. }catch(Exception e){ System.out.println(e);}
21.
22. }
23. }
download this example