JDBC Tutorial
JDBC Tutorial
1. JDBC
2. Why use JDBC?
3. What is API?
This JDBC tutorial covers all the topics of JDBC with the simple
examples. JDBC is a Java API that is used to connect and execute query
to the database. JDBC API uses jdbc drivers to connects to the database.
Before JDBC, ODBC API was used to connect and execute query to the
database. But ODBC API uses ODBC driver that is written in C
language which is plateform dependent and unsecured. That is why Sun
Microsystem has defined its own API (JDBC API) that uses JDBC driver
written in Java language.
Do You Know ?
What is API?
2) JDBC Drivers
In this JDBC tutorial, we will see the 5 steps to connect to the database
in java using JDBC.
In this JDBC tutorial, we will connect a simple java program with the
oracle database.
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
9) Statement interface
In this JDBC tutorial, we will learn what is Statement interface and what
are its methods.
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.
In this JDBC tutorial, we will learn how we can get the metadata of a
table.
In this JDBC tutorial, we will learn how we can get the metadata of a
database.
Let's learn how to store image in the oracle database using JDBC.
Let's see the simple example to retrieve image from the oracle database
using JDBC.
Let's see the simple example to store file in the oracle database using
JDBC.
Let's see the simple example to retrieve file from the oracle database
using JDBC.
JDBC Driver
1. JDBC Drivers
1. JDBC-ODBC bridge driver
2. Native-API driver
3. Network Protocol driver
4. Thin driver
easy to use.
can be easily connected to any database.
Disadvantages:
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:
Disadvantages:
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:
Disadvantage:
There are 5 steps to connect any java application with the database in
java using JDBC. They are as follows:
The forName() method of Class class is used to register the driver class.
This method is used to dynamically load the driver class.
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/testexa
mple","root","admin");//mysql database
Connection
con=DriverManager.getConnection("jdbc:postgresql://localhost:5432/
Emp_dtl","postgres","postgres");//postgres database
1. Statement stmt=con.createStatement();
1. con.close();
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
informations for 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.ge
tString(3));
19.
20. //step5 close the connection object
21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste
the jar file here.
2) set classpath:
temporary
permanent
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.
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.
7. Connection con=DriverManager.getConnection(
8. "jdbc:mysql://localhost:3306/sonoo","root","root");
9.
10. //here sonoo is database name, root is username and passw
ord
11.
12. Statement stmt=con.createStatement();
13.
14. ResultSet rs=stmt.executeQuery("select * from emp");
15.
16. while(rs.next())
17. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.ge
tString(3));
18.
19. con.close();
20.
21. }catch(Exception e){ System.out.println(e);}
22.
23. }
24. }
The above example will fetch all the records of emp table.
2) set classpath:
temporary
permament
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.
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 cu
rrent 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. }}
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. }}
DriverManager class:
The metadata means data about data i.e. we can get further information
from the data.
1. import java.sql.*;
2. class Rsmd{
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. PreparedStatement ps=con.prepareStatement("select * fro
m emp");
11. ResultSet rs=ps.executeQuery();
12.
13. ResultSetMetaData rsmd=rs.getMetaData();
14.
15. System.out.println("Total columns: "+rsmd.getColumnCount
());
16. System.out.println("Column Name of 1st column: "+rsmd.ge
tColumnName(1));
17. System.out.println("Column Type Name of 1st column: "+rs
md.getColumnTypeName(1));
18.
19. con.close();
20.
21. }catch(Exception e){ System.out.println(e);}
22.
23. }
24. }
Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER
Connection interface:
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
Let’s see the simple example of Statement interface to insert, update and
delete the record.
import java.sql.*;
class FetchRecord{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://
localhost:3306/testexample”,”root”,”admin”);
Statement stmt=con.createStatement();
con.close();
}}
ResultSet interface
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:
9) public String
is used to return the data of specified
getString(int
column index of the current row as String.
columnIndex):
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_SE
NSITIVE,ResultSet.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. }}
PreparedStatement interface
As you can see, we are passing parameter (?) for the values. Its value
will be set by calling the setter methods of PreparedStatement.
Method Description
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 qu
ery
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. }
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 emp13
0 values(?,?,?)");
9.
10. BufferedReader br=new BufferedReader(new InputStreamR
eader(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. }}
ResultSetMetaData Interface
The metadata means data about data i.e. we can get further information
from the data.
1. import java.sql.*;
2. class Rsmd{
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. PreparedStatement ps=con.prepareStatement("select * fro
m emp");
11. ResultSet rs=ps.executeQuery();
12.
13. ResultSetMetaData rsmd=rs.getMetaData();
14.
15. System.out.println("Total columns: "+rsmd.getColumnCount
());
16. System.out.println("Column Name of 1st column: "+rsmd.ge
tColumnName(1));
17. System.out.println("Column Type Name of 1st column: "+rs
md.getColumnTypeName(1));
18.
19. con.close();
20.
21. }catch(Exception e){ System.out.println(e);}
22.
23. }
24. }
Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER
DatabaseMetaData interface:
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.
10. DatabaseMetaData dbmd=con.getMetaData();
11.
12. System.out.println("Driver Name: "+dbmd.getDriverName())
;
13. System.out.println("Driver Version: "+dbmd.getDriverVersio
n());
14. System.out.println("UserName: "+dbmd.getUserName());
15. System.out.println("Database Product Name: "+dbmd.getDa
tabaseProductName());
16. System.out.println("Database Product Version: "+dbmd.getD
atabaseProductVersion());
17.
18. con.close();
19.
20. }catch(Exception e){ System.out.println(e);}
21.
22. }
23. }
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. }
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. }
For storing image into the database, BLOB (Binary Large Object)
datatype is used in the table. For example:
Let's write the jdbc code to store the image in the database. Here we are
using d:\\d.jpg for the location of image. You can change it according to
the image location.
1. import java.sql.*;
2. import java.io.*;
3. public class InsertImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("insert into img
table values(?,?)");
11. ps.setString(1,"sonoo");
12.
13. FileInputStream fin=new FileInputStream("d:\\g.jpg");
14. ps.setBinaryStream(2,fin,fin.available());
15. int i=ps.executeUpdate();
16. System.out.println(i+" records affected");
17.
18. con.close();
19. }catch (Exception e) {e.printStackTrace();}
20. }
21. }
If you see the table, record is stored in the database but image will not be
shown. To do so, you need to retrieve the image from the database
which we are covering in the next page.
Now let's write the code to retrieve the image from the database and
write it into the directory so that it can be displayed.
1. import java.sql.*;
2. import java.io.*;
3. public class RetrieveImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("select * from i
mgtable");
11. ResultSet rs=ps.executeQuery();
12. if(rs.next()){//now on 1st row
13.
14. Blob b=rs.getBlob(2);//2 means 2nd column data
15. byte barr[]=b.getBytes(1,(int)b.length());//1 means first imag
e
16.
17. FileOutputStream fout=new FileOutputStream("d:\\
sonoo.jpg");
18. fout.write(barr);
19.
20. fout.close();
21. }//end of if
22. System.out.println("ok");
23.
24. con.close();
25. }catch (Exception e) {e.printStackTrace(); }
26. }
27. }
Syntax:
1. import java.io.*;
2. import java.sql.*;
3.
4. public class StoreFile {
5. public static void main(String[] args) {
6. try{
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. PreparedStatement ps=con.prepareStatement(
12. "insert into filetable values(?,?)");
13.
14. File f=new File("d:\\myfile.txt");
15. FileReader fr=new FileReader(f);
16.
17. ps.setInt(1,101);
18. ps.setCharacterStream(2,fr,(int)f.length());
19. int i=ps.executeUpdate();
20. System.out.println(i+" records affected");
21.
22. con.close();
23.
24. }catch (Exception e) {e.printStackTrace();}
25. }
26. }
Example to retrieve file from Oracle database:
Let's see the table structure of this example to retrieve the file.
The example to retrieve the file from the Oracle database is given below.
1. import java.io.*;
2. import java.sql.*;
3.
4. public class RetrieveFile {
5. public static void main(String[] args) {
6. try{
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. PreparedStatement ps=con.prepareStatement("select * from f
iletable");
12. ResultSet rs=ps.executeQuery();
13. rs.next();//now on 1st row
14.
15. Clob c=rs.getClob(2);
16. Reader r=c.getCharacterStream();
17.
18. FileWriter fw=new FileWriter("d:\\retrivefile.txt");
19.
20. int i;
21. while((i=r.read())!=-1)
22. fw.write((char)i);
23.
24. fw.close();
25. con.close();
26.
27. System.out.println("success");
28. }catch (Exception e) {e.printStackTrace(); }
29. }
30. }
CallableStatement Interface
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.
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. /
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.
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.
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
Method Description
1. import java.sql.*;
2. class FetchRecords{
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. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.executeUpdate("insert into user420 values(190,'abhi',40000)
");
10. stmt.executeUpdate("insert into user420 values(191,'umesh
',50000)");
11.
12. con.commit();
13. con.close();
14. }}
If you see the table emp400, you will see that 2 records has been added.
1. import java.sql.*;
2. import java.io.*;
3. class TM{
4. public static void main(String args[]){
5. try{
6.
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection("jdbc:oracle:thin:
@localhost:1521:xe","system","oracle");
9. con.setAutoCommit(false);
10.
11. PreparedStatement ps=con.prepareStatement("insert into u
ser420 values(?,?,?)");
12.
13. BufferedReader br=new BufferedReader(new InputStreamR
eader(System.in));
14. while(true){
15.
16. System.out.println("enter id");
17. String s1=br.readLine();
18. int id=Integer.parseInt(s1);
19.
20. System.out.println("enter name");
21. String name=br.readLine();
22.
23. System.out.println("enter salary");
24. String s3=br.readLine();
25. int salary=Integer.parseInt(s3);
26.
27. ps.setInt(1,id);
28. ps.setString(2,name);
29. ps.setInt(3,salary);
30. ps.executeUpdate();
31.
32. System.out.println("commit/rollback");
33. String answer=br.readLine();
34. if(answer.equals("commit")){
35. con.commit();
36. }
37. if(answer.equals("rollback")){
38. con.rollback();
39. }
40.
41.
42. System.out.println("Want to add more records y/n");
43. String ans=br.readLine();
44. if(ans.equals("n")){
45. break;
46. }
47.
48. }
49. con.commit();
50. System.out.println("record successfully saved");
51.
52. con.close();//before closing connection commit() is called
53. }catch(Exception e){System.out.println(e);}
54.
55. }}
It will ask to add more records until you press n. If you press n,
transaction is committed.
Fast Performance
Method Description
1. import java.sql.*;
2. class FetchRecords{
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. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.addBatch("insert into user420 values(190,'abhi',40000)");
10. stmt.addBatch("insert into user420 values(191,'umesh',5000
0)");
11.
12. stmt.executeBatch();//executing the batch
13.
14. con.commit();
15. con.close();
16. }}
If you see the table user420, two records has been added.
1. import java.sql.*;
2. import java.io.*;
3. class BP{
4. public static void main(String args[]){
5. try{
6.
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection("jdbc:oracle:thin:
@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("insert into u
ser420 values(?,?,?)");
11.
12. BufferedReader br=new BufferedReader(new InputStreamR
eader(System.in));
13. while(true){
14.
15. System.out.println("enter id");
16. String s1=br.readLine();
17. int id=Integer.parseInt(s1);
18.
19. System.out.println("enter name");
20. String name=br.readLine();
21.
22. System.out.println("enter salary");
23. String s3=br.readLine();
24. int salary=Integer.parseInt(s3);
25.
26. ps.setInt(1,id);
27. ps.setString(2,name);
28. ps.setInt(3,salary);
29.
30. ps.addBatch();
31. System.out.println("Want to add more records y/n");
32. String ans=br.readLine();
33. if(ans.equals("n")){
34. break;
35. }
36.
37. }
38. ps.executeBatch();
39.
40. System.out.println("record successfully saved");
41.
42. con.close();
43. }catch(Exception e){System.out.println(e);}
44.
45. }}
It will add the queries into the batch until user press n. Finally it
executes the batch. Thus all the added queries will be fired.
JDBC RowSet
JdbcRowSet
CachedRowSet
WebRowSet
JoinRowSet
FilteredRowSet
1. import java.sql.Connection;
2. import java.sql.DriverManager;
3. import java.sql.ResultSet;
4. import java.sql.Statement;
5. import javax.sql.RowSetEvent;
6. import javax.sql.RowSetListener;
7. import javax.sql.rowset.JdbcRowSet;
8. import javax.sql.rowset.RowSetProvider;
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = RowSetProvider.newFactory().cre
ateJdbcRowSet();
16. rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
17. rowSet.setUsername("system");
18. rowSet.setPassword("oracle");
19.
20. rowSet.setCommand("select * from emp400");
21. rowSet.execute();
22.
23. while (rowSet.next()) {
24. // Generating cursor Moved event
25. System.out.println("Id: " + rowSet.getString(1))
;
26. System.out.println("Name: " + rowSet.getString
(2));
27. System.out.println("Salary: " + rowSet.getString
(3));
28. }
29.
30. }
31. }
Let's write the code to retrieve the data and perform some additional
tasks while cursor is moved, cursor is changed or rowset is changed. The
event handling operation can't be performed using ResultSet so it is
preferred now.
1. import java.sql.Connection;
2. import java.sql.DriverManager;
3. import java.sql.ResultSet;
4. import java.sql.Statement;
5. import javax.sql.RowSetEvent;
6. import javax.sql.RowSetListener;
7. import javax.sql.rowset.JdbcRowSet;
8. import javax.sql.rowset.RowSetProvider;
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = RowSetProvider.newFactory().creat
eJdbcRowSet();
16. rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
17. rowSet.setUsername("system");
18. rowSet.setPassword("oracle");
19.
20. rowSet.setCommand("select * from emp400");
21. rowSet.execute();
22.
23. //Adding Listener and moving RowSet
24. rowSet.addRowSetListener(new MyListener());
25.
26. while (rowSet.next()) {
27. // Generating cursor Moved event
28. System.out.println("Id: " + rowSet.getString(1))
;
29. System.out.println("Name: " + rowSet.getString
(2));
30. System.out.println("Salary: " + rowSet.getString
(3));
31. }
32.
33. }
34. }
35.
36. class MyListener implements RowSetListener {
37. public void cursorMoved(RowSetEvent event) {
38. System.out.println("Cursor Moved...");
39. }
40. public void rowChanged(RowSetEvent event) {
41. System.out.println("Cursor Changed...");
42. }
43. public void rowSetChanged(RowSetEvent event) {
44. System.out.println("RowSet changed...");
45. }
46. }