JDBC
JDBC
JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute
the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses
JDBC drivers to connect with the database. There are four types of JDBC drivers:
We can use JDBC API to access tabular data stored in any relational database. By the help
of JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is
based on the X/Open SQL Call Level Interface. The java.sql package contains classes and
interfaces for JDBC API. A list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
o DriverManager class
o Blob class
o Clob class
o Types class
We can use JDBC API to handle database using Java program and can perform the
following activities:
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 a 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 typ
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)
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that
you use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC
Bridge.
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
database API. It is not written entirely in java.
Advantage:
Disadvantage:
o No client side library is required because of application server that can perform many tasks
like auditing, load balancing, logging etc.
Disadvantages:
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as
written in Java language.
Advantage:
Disadvantage:
1. Class.forName("oracle.jdbc.driver.OracleDriver");
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the SQL query t
1. create table emp(id number(10),name varchar2(40),age number(3));
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:
There are two ways to set the classpath:
o temporary
o permanent
Firstly, search the ojdbc14.jar file then open command prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
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, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password 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. 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 jar file mysql-connector.jar
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) Set classpath:
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
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 DriverManager class is the component of JDBC API and also a member of
the java.sql package. The DriverManager class acts as an interface between users and
drivers. It keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver. It contains all the appropriate
methods to register and deregister the database driver class and to create a connection
between a Java application and the database. The DriverManager class maintains a list of
Driver classes that have registered themselves by calling the method
DriverManager.registerDriver(). Note that before interacting with a Database, it is a
mandatory process to register the driver; otherwise, an exception is thrown.
Methods of the DriverManager Class
Method Description
1) public static synchronized void is used to register the given driver with DriverManager. No actio
registerDriver(Driver driver): the method when the given driver is already registered.
2) public static synchronized void is used to deregister the given driver (drop the driver fr
deregisterDriver(Driver driver): DriverManager. If the given driver has been removed from the
is performed by the method.
3) public static Connection is used to establish the connection with the specified url. Th
getConnection(String url) throws thrown when the corresponding Driver class of the given databa
SQLException: with the DriverManager.
4) public static Connection is used to establish the connection with the specified url, userna
getConnection(String url,String The SQLException is thrown when the corresponding Driver
userName,String password) throws database is not registered with the DriverManager.
SQLException:
5) public static Driver getDriver(String Those drivers that understand the mentioned URL (present in th
url) method) are returned by this method provided those drivers are
list of registered drivers.
6) pubic static int getLoginTimeout() The duration of time a driver is allowed to wait in order to esta
with the database is returned by this method.
7) pubic static void setLoginTimeout(int The method provides the time in seconds. sec mentioned in th
sec) maximum time that a driver is allowed to wait in order to esta
with the database. If 0 is passed in the parameter of this meth
have to wait infinitely while trying to establish the connection w
8) public static Connection A connection object is returned by this method after creating a
getConnection(String URL, Properties database present at the mentioned URL, which is the first parame
prop) throws SQLException The second parameter, which is "prop", fetches the authentica
database (username and password.). Similar to the other
getConnection() method, this method also throws the SQLEx
corresponding Driver class of the given database is not re
DriverManager.
Connection interface
A Connection is a session between a Java application and a database. It helps to establish
a connection with the database.
4) public void commit(): saves the changes made since the previous commit/rollback is
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.
Connection Interface Fields
There are some common Connection interface constant fields that are present in the
Connect interface. These fields specify the isolation level of a transaction.
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.
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, inse
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.
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:
2) public boolean previous(): is used to move the cursor to the one row previous from the curr
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 row): is used to move the cursor to the specified row number in the Re
6) public boolean relative(int row): is used to move the cursor to the relative row number in the Resu
be positive or negative.
7) public int getInt(int columnIndex): is used to return the data of specified column index of the curren
8) public int getInt(String columnName): is used to return the data of specified column name of the curren
9) public String getString(int is used to return the data of specified column index of the curren
columnIndex):
10) public String getString(String is used to return the data of specified column name of the curren
columnName):
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","sy
stem","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. }}
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
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
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.
public void setString(int paramIndex, String value) sets the String value to the given parameter index.
public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.
public void setDouble(int paramIndex, double value) sets the double value to the given parameter index.
public int executeUpdate() executes the query. It is used for create, drop, insert, up
public ResultSet executeQuery() executes the select query. It returns an instance of Resu
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. }
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","sy
stem","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. }}
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.
public String getColumnName(int index)throws SQLException it returns the column name of the specified
public String getColumnTypeName(int index)throws it returns the column type name for the sp
SQLException
public String getTableName(int index)throws SQLException it returns the table name for the specified c
How to get the object of ResultSetMetaData:
The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax:
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.getColumnTypeNa
me(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
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.getDatabaseProductVersi
on());
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
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. }
4. throws SQLException
For storing image into the database, BLOB (Binary Large Object) datatype is used in the
table. For example:oForward Skip 10s
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.
In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be displayed
by the img tag.
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 imgtable");
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 image
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:
For storing file into the database, CLOB (Character Large Object) datatype is used in the
table. For example:
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 filetable");
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. }
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.
PlayNext
Unmute
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
must not have the return type. must have the return type.
We can call functions from the procedure. Procedure cannot be called from function
Procedure supports input and output parameters. Function supports only input parameter.
Exception handling using try/catch block can be used in Exception handling using try/catch can't
stored procedures. defined functions.
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.
The Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE,
BLOB, CLOB etc.
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
The ACID properties describes the transaction management well. ACID stands for
Atomicity, Consistency, isolation and durability.
Consistency ensures bringing the database from one consistent state to another
consistent state.
Durability means once a transaction has been committed, it will remain so, even in the
event of errors, power loss etc.
fast performance It makes the performance fast because database is hit at the time of
commit.
In JDBC, Connection interface provides methods to manage transaction.
Method Description
void setAutoCommit(boolean status) It is true bydefault means each transaction is committed bydefa
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","sy
stem","oracle");
9. con.setAutoCommit(false);
10.
11. PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");
12.
13. BufferedReader br=new BufferedReader(new InputStreamReader(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. }}