You are on page 1of 41

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.

Why use JDBC


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).

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
Topics in Java JDBC Tutorial

2) JDBC Drivers

In this JDBC tutorial, we will learn 4 types of JDBC drivers, their advantages and
disadvantages.

3) 5 Steps to connect to the database

In this JDBC tutorial, we will see the 5 steps to connect to the database in java using JDBC.

4) Connectivity with Oracle using JDBC

In this JDBC tutorial, we will connect a simple java program with the oracle database.

5) Connectivity with MySQL using JDBC

In this JDBC tutorial, we will connect a simple java program with the mysql database.

6) Connectivity with Access without DSN

Let's connect java application with access database with and without DSN.

7) DriverManager class

In this JDBC tutorial, we will learn what does the DriverManager class and what are its
methods.

8) Connection interface

In this JDBC tutorial, we will learn what is Connection interface and what are its methods.
9) Statement interface

In this JDBC tutorial, we will learn what is Statement interface and what are its methods.

10) ResultSet interface

In this JDBC tutorial, we will learn what is ResultSet interface and what are its methods.
Moreover, we will learn how we can make the ResultSet scrollable.

11) PreparedStatement Interface

In this JDBC tutorial, we will learn what is benefit of PreparedStatement over Statement
interface. We will see examples to insert, update or delete records using the
PreparedStatement interface.

12) ResultSetMetaData interface

In this JDBC tutorial, we will learn how we can get the metadata of a table.

13) DatabaseMetaData interface

In this JDBC tutorial, we will learn how we can get the metadata of a database.

14) Storing image in Oracle

Let's learn how to store image in the oracle database using JDBC.

15) Retrieving image from Oracle

Let's see the simple example to retrieve image from the oracle database using JDBC.

16) Storing file in Oracle

Let's see the simple example to store file in the oracle database using JDBC.
17) Retrieving file from Oracle

Let's see the simple example to retrieve file from the oracle database using JDBC.

18) CallableStatement

Let's see the code to call stored procedures and functions using CallableStatement.

19) Transaction Management using JDBC

Let's see the simple example to use transaction management using JDBC.

20) Batch Statement using JDBC

Let's see the code to execute batch of queries.

21) JDBC RowSet

Let's see the working of new JDBC RowSet interface.


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)

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. 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:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.

o The Vendor client library needs to be installed on client machine.


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. 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:

o Network support is required on client machine.

o Requires database-specific coding to be done in the middle tier.

o 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.
That is why it is known as thin driver. It is fully written in Java language.

Advantage:

o Better performance than all other drivers.

o No software is required at client side or server side.

Disadvantage:

o Drivers depends on the Database.


5 Steps to connect to the database in
java
1. 5 Steps to connect to the database in java
1. Register the driver class
2. Create the connection object
3. Create the Statement object
4. Execute the query
5. Close the connection object

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

1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.

Syntax of forName() method

1. public static void forName(String className)throws ClassNotFoundException  

Example to register the OracleDriver class


1. Class.forName("oracle.jdbc.driver.OracleDriver");  

2) Create the connection object

The getConnection() method of DriverManager class is used to establish connection with


the database.

Syntax of getConnection() method

1. 1) public static Connection getConnection(String url)throws SQLException  
2. 2) public static Connection getConnection(String url,String name,String password)  
throws SQLException  

Example to establish connection with the Oracle database


1. Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","password");  

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The


object of statement is responsible to execute queries with the database.

Syntax of createStatement() method

1. public Statement createStatement()throws SQLException  

Example to create the statement object


1. Statement stmt=con.createStatement();  

4) Execute the query

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.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException  

Example to execute query


1. ResultSet rs=stmt.executeQuery("select * from emp");  
2.   
3. while(rs.next()){  
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));  
5. }  

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.

Syntax of close() method

1. public void close()throws SQLException  

Example to close connection


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.

Let's first create a table in oracle database.


1. create table emp(id number(10),name varchar2(40),age number(3));  

Example to Connect Java Application with 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.

download the jar file ojdbc14.jar

Two ways to load the jar file:

1. paste the ojdbc14.jar file in jre/lib/ext folder


2. set classpath

1) paste the ojdbc14.jar file in JRE/lib/ext folder:

Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.

2) set classpath:

There are two ways to set the classpath:


o temporary

o permanent

How to set the temporary classpath:

Firstly, search the ojdbc14.jar file then open command prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;  

How to set the permanent classpath:


Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;
Example to connect to the mysql
database in java
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:

1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.

2. Connection URL: The connection URL for the mysql database


is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the
database, localhost is the server name on which mysql is running, we may also use
IP address, 3306 is the port number and sonoo is the database name. We may use
any database, in such case, you need to replace the sonoo with your database name.

3. Username: The default username for the mysql database is root.

4. Password: Password is given by the user at the time of installing the mysql


database. In this example, we are going to use root as the password.

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));  
Example to Connect Java Application with mysql database
In this example, sonoo is the database name, root is the username and password.

import java.sql.*;  
class MysqlCon{  
public static void main(String args[]){  
try{  
Class.forName("com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection(  
"jdbc:mysql://localhost:3306/sonoo","root","root");  
//here sonoo is database name, root is username and password  
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery("select * from emp");  
while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
con.close();  
}catch(Exception e){ System.out.println(e);}  
}  
}  

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 jar file mysql-connector.jar


Two ways to load the jar file:

1. paste the mysqlconnector.jar file in jre/lib/ext folder

2. set classpath

1) paste the mysqlconnector.jar file in JRE/lib/ext


folder:

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 set the classpath:


o temporary

o permanent

How to set the temporary classpath

open command prompt and write:


1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;  

How to set the permanent classpath


Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending
mysqlconnector.jar;.; as C:\folder\mysql-connector-java-5.0.8-bin.jar;.;
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.

Commonly used methods of Statement interface:


The important methods of Statement interface are as follows:

1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It


returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be
create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return
multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.

Example of Statement interface


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 w
here id=33");  
10. int result=stmt.executeUpdate("delete from emp765 where id=33");  
11. System.out.println(result+" records affected");  
12. con.close();  
13. }} 

PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.

Let's see the example of parameterized query:

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.

Why use PreparedStatement?


Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.

How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the object of


PreparedStatement. Syntax:

1. public PreparedStatement prepareStatement(String query)throws SQLException{}  
Methods of PreparedStatement interface
The important methods of PreparedStatement interface are given below:

Method Description

public void setInt(int paramIndex, int sets the integer value to the given parameter index.
value)

public void setString(int paramIndex, sets the String value to the given parameter index.
String value)

public void setFloat(int paramIndex, float sets the float value to the given parameter index.
value)

public void setDouble(int paramIndex, sets the double value to the given parameter index.
double value)

public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance of


ResultSet.

Example of PreparedStatement interface that inserts


the record
First of all create table as given below:

1. create table emp(id number(10),name varchar2(50));  

Now insert records in this table by the code given below:

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

Example of PreparedStatement interface that


updates the record

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

Example of PreparedStatement interface that


retrieve the records of a table

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

Example of PreparedStatement to insert records


until user press n

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. }}  

Java CallableStatement Interface


CallableStatement interface is used to call the stored procedures and functions.

We can have business logic on the database by the use of stored procedures and functions
that will make the performance better because these are precompiled.

Suppose you need the get the age of the employee based on the date of birth, you may
create a function that receives date as the input and returns age of the employee as the
output.
What is the difference between stored procedures
and functions.
The differences between stored procedures and functions are given below:

Stored Procedure Function

is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.

may return 0 or more values. may return only one values.

We can call functions from the procedure. Procedure cannot be called from function.

Procedure supports input and output Function supports only input parameter.
parameters.

Exception handling using try/catch block can be Exception handling using try/catch can't be used
used in stored procedures. in user defined functions.

How to get the instance of CallableStatement?


The prepareCall() method of Connection interface returns the instance of CallableStatement.
Syntax is given below:

1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");  

The example to get the instance of CallableStatement is given below:

1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");  

It calls the procedure myprocedure that receives 2 arguments.

Full example to call the stored procedure using JDBC


To call the stored procedure, you need to create it in the database. Here, we are assuming
that stored procedure looks like this.
1. create or replace procedure "INSERTR"  
2. (id IN NUMBER,  
3. name IN VARCHAR2)  
4. is  
5. begin  
6. insert into user420 values(id,name);  
7. end;  
8. /     

The table structure is given below:

1. create table user420(id number(10), name varchar2(200));  

In this example, we are going to call the stored procedure INSERTR that receives id and
name as the parameter and inserts it into the table user420. Note that you need to create
the user420 table as well to run this application.

1. import java.sql.*;  
2. public class Proc {  
3. public static void main(String[] args) throws Exception{  
4.   
5. Class.forName("oracle.jdbc.driver.OracleDriver");  
6. Connection con=DriverManager.getConnection(  
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
8.   
9. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");  
10. stmt.setInt(1,1011);  
11. stmt.setString(2,"Amit");  
12. stmt.execute();  
13.   
14. System.out.println("success");  
15. }  
16. }  

Now check the table in the database, value is inserted in the user420 table.

Example to call the function using JDBC


In this example, we are calling the sum4 function that receives two input and returns the
sum of the given number. Here, we have used the registerOutParameter method of
CallableStatement interface, that registers the output parameter with its corresponding
type. It provides information to the CallableStatement about the type of result being
displayed.

The Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE,


BLOB, CLOB etc.

Let's create the simple function in the database first.

1. create or replace function sum4  
2. (n1 in number,n2 in number)  
3. return number  
4. is   
5. temp number(8);  
6. begin  
7. temp :=n1+n2;  
8. return temp;  
9. end;  
10. /  

Now, let's write the simple program to call the function.

1. import java.sql.*;  
2.   
3. public class FuncSum {  
4. public static void main(String[] args) throws Exception{  
5.   
6. Class.forName("oracle.jdbc.driver.OracleDriver");  
7. Connection con=DriverManager.getConnection(  
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
9.   
10. CallableStatement stmt=con.prepareCall("{?= call sum4(?,?)}");  
11. stmt.setInt(2,10);  
12. stmt.setInt(3,43);  
13. stmt.registerOutParameter(1,Types.INTEGER);  
14. stmt.execute();  
15.   
16. System.out.println(stmt.getInt(1));  
17.           
18. }  
19. }  
Output: 53

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);  

Commonly used methods of ResultSet interface

1) public boolean next(): is used to move the cursor to the one row next from t
current position.

2) public boolean previous(): is used to move the cursor to the one row previous from t
current position.

3) public boolean first(): is used to move the cursor to the first row in result set objec

4) public boolean last(): is used to move the cursor to the last row in result set objec

5) public boolean absolute(int is used to move the cursor to the specified row number in t
row): ResultSet object.
6) public boolean relative(int is used to move the cursor to the relative row number in t
row): ResultSet object, it may be positive or negative.

7) public int getInt(int is used to return the data of specified column index of t
columnIndex): current row as int.

8) public int getInt(String is used to return the data of specified column name of t
columnName): current row as int.

9) public String getString(int is used to return the data of specified column index of t
columnIndex): current row as String.

10) public String getString(String is used to return the data of specified column name of t
columnName): current row as String.

Example of Scrollable ResultSet


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,ResultSe
t.CONCUR_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. }}  

Java ResultSetMetaData Interface


The metadata means data about data i.e. we can get further information from the data.

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.

Commonly used methods of ResultSetMetaData interface


Method Description

public int getColumnCount()throws SQLException it returns the total number of columns in the
ResultSet object.

public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.

public String getColumnTypeName(int index)throws it returns the column type name for the
SQLException specified index.

public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.

How to get the object of ResultSetMetaData:

The getMetaData() method of ResultSet interface returns the object of


ResultSetMetaData. Syntax:

1. public ResultSetMetaData getMetaData()throws SQLException  

Example of ResultSetMetaData interface :

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

JDBC and AWT

import java.awt.*;

import java.sql.*;
import javax.swing.*;
import java.awt.event.*;

class  FormData{
    public static void main(String[] args){
    Frame f=new Frame();
    Label label1=new Label("First Name: ");
    Label label2=new Label("Last Name: ");
    Label label3=new Label("Email: ");
    Label label4=new Label("Address: ");
    Label label5=new Label("Contact No: ");
    final TextField text1=new TextField(20);
    final TextField text2=new TextField(20);
    final TextField text3=new TextField(20);
    final TextField text4=new TextField(20);
    final TextField text5=new TextField(20);
    Button b=new Button("Save");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
        String v1=text1.getText();
        String v2=text2.getText();
        String v3=text3.getText();
        String v4=text4.getText();
        String v5=text5.getText();
        try{
           Class.forName("com.mysql.jdbc.Driver");
           Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/roseindia", "root",
"root");
           Statement st=con.createStatement();
           int i=st.executeUpdate("insert into
student(firstname,lastname,email,address,telephone)
values('"+v1+"','"+v2+"','"+v3+"','"+v4+"','"+v5+"')");
           JOptionPane.showMessageDialog(null,"Data is inserted
successfully");
        }
        catch(Exception ex){
        System.out.println(ex);
         }
       }
        });
        Panel p=new Panel(new GridLayout(6,2));
        p.add(label1);
        p.add(text1);
        p.add(label2);
        p.add(text2);
        p.add(label3);
        p.add(text3);
        p.add(label4);
        p.add(text4);
        p.add(label5);
        p.add(text5);
        p.add(b);
        f.add(p);
        f.setVisible(true);
        f.pack();
    }
}

Connection pooling

Introduction
This document provides information intended to help developers provide a connection
pooling strategy for applications that must handle connection pooling. First, this
document provides an overview of JDBC connection pooling as specified by the JDBC
3.0 specification. Next, it provides examples of how to use the DataDirect Connection
Pool Manager (which is shipped with DataDirect Connect® for JDBC and DataDirect
SequeLink® for JDBC) for your applications. Finally, this document provides an
example showing performance benchmarks that demonstrate the performance benefit
you can achieve by using connection pooling.

Back to top

Connection Pooling
Establishing JDBC connections is resource-expensive, especially when the JDBC API is
used in a middle-tier server environment, such as when DataDirect Connect for JDBC
or DataDirect SequeLink for JDBC is running on a Java-enabled web server. In this type
of environment, performance can be improved significantly when connection pooling is
used. Connection pooling means that connections are reused rather than created each
time a connection is requested. To facilitate connection reuse, a memory cache of
database connections, called a connection pool, is maintained by a connection pooling
module as a layer on top of any standard JDBC driver product.

Connection pooling is performed in the background and does not affect how an
application is coded; however, the application must use a DataSource object (an object
implementing the DataSource interface) to obtain a connection instead of using the
DriverManager class. A class implementing the DataSource interface may or may not
provide connection pooling. A DataSource object registers with a JNDI naming service.
Once a DataSource object is registered, the application retrieves it from the JNDI
naming service in the standard way.

For example:
Context ctx = new InitialContext();

DataSource ds = (DataSource) ctx.lookup("jdbc/SequeLink");

If the DataSource object provides connection pooling, the lookup returns a connection
from the pool if one is available. If the DataSource object does not provide connection
pooling or if there are no available connections in the pool, the lookup creates a new
connection. The application benefits from connection reuse without requiring any code
changes. Reused connections from the pool behave the same way as newly created
physical connections. The application makes a connection to the database and data
access works in the usual way. When the application has finished its work with the
connection, the application explicitly closes the connection.

For example:

Connection con = ds.getConnection("scott", "tiger");

// Do some database activities using the connection...

con.close();

The closing event on a pooled connection signals the pooling module to place the
connection back in the connection pool for future reuse.

JDBC Tutorial: SQL Insert, Select, Update, and


Delete Examples
Last Updated on 07 August 2017   |    Print   Email
Java Spring Framework Masterclass: Beginner to Professional
This tutorial is going to help you learning how to do basic database operations
(CRUD - Create, Retrieve, Update and Delete) using JDBC (Java Database
Connectivity) API. These CRUD operations are equivalent to the INSERT,
SELECT, UPDATE and DELETE statements in SQL language. Although the target
database system is MySQL, but the same technique can be applied for other
database systems as well because the query syntax used is standard SQL which
is supported by all relational database systems.
We will learn how to do insert, query, update and delete database records by
writing code to manage records of a table Users in a MySQL database
called SampleDB.
Table of content:

1.
1. Prerequisites
2. Creating a sample MySQL database
3. The principal JDBC interfaces and classes
4. Connecting to the database
5. Executing INSERT statement
6. Executing SELECT statement
7. Executing UPDATE statement
8. Executing DELETE statement

1. Prerequisites
To begin, make sure you have the following pieces of software installed on your
computer:

o JDK (download JDK 7).
o MySQL (download MySQL Community Server 5.6.12). You may also
want to download MySQL Workbench - a graphical tool for working with
MySQL databases.
o JDBC Driver for MySQL (download MySQL Connector/J 5.1.25).
Extract the zip archive and put the mysql-connector-java-5.1.25-
bin.jar file into classpath (in a same folder as your Java source files).

2. Creating a sample MySQL database


Let’s create a MySQL database called SampleDB with one table Users with the
following structure:
Execute the following SQL script inside MySQL Workbench:
1
2 create database SampleDB;
3  
use SampleDB;
4
 
5 CREATE TABLE `users` (
6     `user_id` int(11) NOT NULL AUTO_INCREMENT,
7     `username` varchar(45) NOT NULL,
8     `password` varchar(45) NOT NULL,
    `fullname` varchar(45) NOT NULL,
9
    `email` varchar(45) NOT NULL,
10     PRIMARY KEY (`user_id`)
11 );
12
Or if you are using MySQL Command Line Client program, save the above script
into a file, let’s say, SQLScript.sql and execute the following command:
source Path\To\The\Script\File\SQLScript.sql

Here’s an example screenshot taken while executing the above script in MySQL
Command Line Clientprogram:

3. The principal JDBC interfaces and classes


Let’s take an overview look at the JDBC’s main interfaces and classes with
which we usually work. They are all available under the java.sql package:

o DriverManager: this class is used to register driver for a specific
database type (e.g. MySQL in this tutorial) and to establish a database
connection with the server via its getConnection() method.
o Connection: this interface represents an established database
connection (session) from which we can create statements to execute
queries and retrieve results, get metadata about the database, close
connection, etc.
o Statement and PreparedStatement: these interfaces are used to
execute static SQL query and parameterized SQL query,
respectively. Statement is the super interface of
the PreparedStatementinterface. Their commonly used methods are:

I.
o
 boolean execute(String sql): executes a general SQL
statement. It returns true if the query returns a ResultSet, false if
the query returns an update count or returns nothing. This method can
be used with a Statement only.
 int executeUpdate(String sql): executes an INSERT, UPDATE
or DELETE statement and returns an update account indicating number
of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0 rows
affected).
 ResultSet executeQuery(String sql): executes a SELECT
statement and returns a ResultSet object which contains results
returned by the query.

A prepared statement is one that contains placeholders (in form question


marks ?) for dynamic values will be set at runtime. For example:
SELECT * from Users WHERE user_id=?

Here the value of user_id is parameterized by a question mark and will


be set by one of the setXXX() methods from
the PreparedStatement interface, e.g. setInt(int index, int value).

o ResultSet: contains table data returned by a SELECT query. Use this
object to iterate over rows in the result set using next() method, and get
value of a column in the current row using getXXX() methods
(e.g. getString(), getInt(), getFloat() and so on). The column value can
be retrieved either by index number (1-based) or by column name.
o SQLException: this checked exception is declared to be thrown by all
the above methods, so we have to catch this exception explicitly when
calling the above classes’ methods.  
Practical Database Programming with Java  - This book is for those who are
beginner in Java database programming and want to catch up with the main
database programming techniques with straightforward and easy to learn
example code.

4. Connecting to the database


Supposing the MySQL database server is listening on the default
port 3306 at localhost. The following code snippet connects to the database
name SampleDB by the user root and password secret:
1
2 String dbURL = "jdbc:mysql://localhost:3306/sampledb";
String username = "root";
3 String password = "secret";
4
 
5 try {
6  
7     Connection conn = DriverManager.getConnection(dbURL, username, password);
8  
9     if (conn != null) {
10         System.out.println("Connected");
    }
11 } catch (SQLException ex) {
12     ex.printStackTrace();
13 }
14
Once the connection was established, we have a Connection object which can
be used to create statements in order to execute SQL queries. In the above
code, we have to close the connection explicitly after finish working with the
database:
1 conn.close();
However, since Java 7, we can take advantage of the try-with-resources
statement which will close the connection automatically, as shown in the
following code snippet:
1 try (Connection conn = DriverManager.getConnection(dbURL, username, password)) {
2      
3     // code to execute SQL queries goes here...
4      
5 } catch (SQLException ex) {
6     ex.printStackTrace();
}
7
If you are using Java 7 or later, this approach is recommended. The sample
programs in this tutorial are all using this try-with-resources statement to make
a database connection.
NOTE: For details about connecting to a MySQL database, see the
article: Connect to MySQL database via JDBC.
 
5. Executing INSERT statement
Let’s write code to insert a new record into the table Users with following
details:

o username: bill
o password: secretpass
o fullname: Bill Gates
o email: bill.gates@microsoft.com

Here’s the code snippet:


1 String sql = "INSERT INTO Users (username, password, fullname, email) VALUES (?, ?,
2 ?, ?)";
3  
4 PreparedStatement statement = conn.prepareStatement(sql);
5 statement.setString(1, "bill");
statement.setString(2, "secretpass");
6 statement.setString(3, "Bill Gates");
7 statement.setString(4, "bill.gates@microsoft.com");
8  
9 int rowsInserted = statement.executeUpdate();
10 if (rowsInserted > 0) {
11     System.out.println("A new user was inserted successfully!");
}
12
In this code, we create a parameterized SQL INSERT statement and create
a PreparedStatement from the Connection object. To set values for the
parameters in the INSERT statement, we use
the PreparedStatement‘s setString() methods because all these columns in the
table Users are of type VARCHAR which is translated to String type in Java.
Note that the parameter index is 1-based (unlike 0-based index in Java array).
The PreparedStatement interface provides various setXXX() methods
corresponding to each data type, for example:

o setBoolean(int parameterIndex, boolean x)
o setDate(int parameterIndex, Date x)
o setFloat(int parameterIndex, float x)
o …
And so on. Which method to be used is depending on the type of the
corresponding column in the database table.
Finally we call the PreparedStatement’s executeUpdate() method to execute the
INSERT statement. This method returns an update count indicating how many
rows in the table were affected by the query, so checking this return value is
necessary to ensure the query was executed successfully. In this
case, executeUpdate()method should return 1 to indicate one record was
inserted.
 
Recommended Book: Getting Started with NoSQL

6. Executing SELECT statement


The following code snippet queries all records from the Users table and print
out details for each record:
1
String sql = "SELECT * FROM Users";
2
 
3 Statement statement = conn.createStatement();
4 ResultSet result = statement.executeQuery(sql);
5  
6 int count = 0;
7  
8 while (result.next()){
    String name = result.getString(2);
9     String pass = result.getString(3);
10     String fullname = result.getString("fullname");
11     String email = result.getString("email");
12  
13     String output = "User #%d: %s - %s - %s - %s";
14     System.out.println(String.format(output, ++count, name, pass, fullname,
email));
15 }
16
Output:
User #1: bill - secretpass - Bill Gates - bill.gates@microsoft.com

Because the SQL SELECT query here is static so we just create


a Statement object from the connection. The while loop iterates over the rows
contained in the result set by repeatedly checking return value of
the ResultSet’s next() method. The next() method moves a cursor forward in
the result set to check if there is any remaining record. For each iteration, the
result set contains data for the current row, and we use
the ResultSet’s getXXX(column index/column name) method to retrieve value of a
specific column in the current row, for example this statement:
1 String name = result.getString(2);
Retrieves value of the second column in the current row, which is
the username field. The value is casted to a String because we know that
the username field is of type VARCHAR based on the database schema
mentioned previously. Keep in mind that the column index here is 1-based, the
first column will be at index 1, the second at index 2, and so on. If you are not
sure or don’t know exactly the index of column, so passing a column name would
be useful:
1 String fullname = result.getString("fullname");
For other data types, the ResultSet provide appropriate getter methods:

o getString()
o getInt()
o getFloat()
o getDate()
o getTimestamp()
o …

TIPS: Accessing column’s value by column index would provide faster


performance then column name.
 
 

7. Executing UPDATE statement


The following code snippet will update the record of “Bill Gates” as we inserted
previously:
1
2 String sql = "UPDATE Users SET password=?, fullname=?, email=? WHERE username=?";
3  
PreparedStatement statement = conn.prepareStatement(sql);
4 statement.setString(1, "123456789");
5 statement.setString(2, "William Henry Bill Gates");
6 statement.setString(3, "bill.gates@microsoft.com");
7 statement.setString(4, "bill");
8  
int rowsUpdated = statement.executeUpdate();
9
if (rowsUpdated > 0) {
10     System.out.println("An existing user was updated successfully!");
11 }
12
This code looks very similar to the INSERT code above, except the query type is
UPDATE.

8. Executing DELETE statement


The following code snippet will delete a record whose username field contains
“bill”:
1 String sql = "DELETE FROM Users WHERE username=?";
2  
PreparedStatement statement = conn.prepareStatement(sql);
3
statement.setString(1, "bill");
4
5  
6 int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
7     System.out.println("A user was deleted successfully!");
8 }
9

You might also like