0% found this document useful (0 votes)
18 views31 pages

Unit V R2

Uploaded by

kishore0331
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views31 pages

Unit V R2

Uploaded by

kishore0331
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Java JDBC Tutorial

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:

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver

We have discussed the above four drivers in the next chapter.

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:
Play Videox

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

A list of popular classes of JDBC API are given below:

o DriverManager class
o Blob class
o Clob class
o Types class

Why Should We Use JDBC

Before JDBC, ODBC API was the database API to connect and execute the 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).

We can use JDBC API to handle database using Java program and can perform the
following activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

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.

Topics in Java JDBC Tutorial

2) JDBC Drivers

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

3) 5 Steps to connect to the Database


In this JDBC tutorial, we will see the five 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.
In Java 8, the JDBC-ODBC Bridge has been removed.

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 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 depend on the Database.

Java Database Connectivity with 5 Steps

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 using JDBC. These steps are

o Register the Driver class


o Create connection
o Create statement
o Execute queries
o Close connection

1) Register the driver class

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

Syntax of forName() method

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


Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to
put vender's Jar in the classpath, and then JDBC driver manager can detect and
load the driver automatically.

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

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 da

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
)
3. throws SQLException

Example to establish connection with the Oracle database

1. Connection con=DriverManager.getConnection(
2. "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
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. T
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(
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();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to
automatically close resources of type Connection, ResultSet, and Statement.

It avoids explicit connection closing step.

ava Database Connectivity with Oracle

To connect java application with the oracle database, we need to follow 5 following steps. In th
we are using Oracle 10g as the database. So we need to know following information for the orac
1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver
2. Connection URL: The connection URL for the oracle10G
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database
driver, localhost is the server name on which oracle is running, we may also use IP addr
the port number and XE is the Oracle service name. You may get all these informati
tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle database

Create a Table

Before establishing connection, let's first create a table in oracle database. Following is the SQ
create a table.
1. create table emp(id number(10),name varchar2(40),age number(3));

Example to Connect Java Application with Oracle database

In this example, we are connecting to an Oracle database and getting data


from emp table. Here, system and oracle are the username and password of the
Oracle database.

import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


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

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


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

//step5 close the connection object


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

ava Database Connectivity with MySQL

To connect Java application with the MySQL database, we need to follow 5


following steps.

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

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

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 DriverM
registerDriver(Driver driver): action is performed by the method when the give
already registered.

2) public static synchronized void is used to deregister the given driver (drop the driv
deregisterDriver(Driver driver): list) with DriverManager. If the given driver
removed from the list, then no action is perform
method.

3) public static Connection is used to establish the connection with the specifi
getConnection(String url) throws SQLException is thrown when the corresponding D
SQLException: of the given database is not registered
DriverManager.

4) public static Connection is used to establish the connection with the sp


getConnection(String url,String username, and password. The SQLException is th
userName,String password) throws the corresponding Driver class of the given data
SQLException: registered with the DriverManager.

5) public static Driver getDriver(String Those drivers that understand the mentioned URL
url) the parameter of the method) are returned by t
provided those drivers are mentioned in the list o
drivers.

6) pubic static int getLoginTimeout() The duration of time a driver is allowed to wait
establish a connection with the database is return
method.

7) pubic static void The method provides the time in seconds. sec m
setLoginTimeout(int sec) the parameter is the maximum time that a driver is
wait in order to establish a connection with the da
is passed in the parameter of this method, the drive
to wait infinitely while trying to establish the conn
the database.

8) public static Connection A connection object is returned by this method afte


getConnection(String URL, Properties connection to the database present at the mentio
prop) throws SQLException which is the first parameter of this method. T
parameter, which is "prop", fetches the authentica
of the database (username and password.). Similar
variation of the getConnection() method, this m
throws the SQLException, when the correspond
class of the given database is not registered
DriverManager.

Connection interface

A Connection is a session between a Java application and a database. It helps to


establish a connection with the database.

The Connection interface is a factory of Statement, PreparedStatement, and


DatabaseMetaData, i.e., an object of Connection can be used to get the object of
Statement and DatabaseMetaData. The Connection interface provide many
methods for transaction management like commit(), rollback(), setAutoCommit(),
setTransactionIsolation(), etc.
By default, connection commits the changes after executing queries.

Commonly used methods of Connection interface:

1) public Statement createStatement(): creates a statement object that can be


used to execute SQL queries.

2) public Statement createStatement(int resultSetType,int


resultSetConcurrency): Creates a Statement object that will generate ResultSet
objects with the given type and concurrency.

3) public void setAutoCommit(boolean status): is used to set the commit status.


By default, it is true.

4) public void commit(): saves the changes made since the previous
commit/rollback 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.

TRANSACTION_NONE: No transaction is supported, and it is indicated by this


constant.

TRANSACTION_READ_COMMITTED: It is a constant which shows that the


dirty reads are not allowed. However, phantom reads and non-repeatable reads can
occur.

TRANSACTION_READ_UNCOMMITTED: It is a constant which shows that


dirty reads, non-repeatable reads, and phantom reads can occur.

TRANSACTION_REPEATABLE_READ: It is a constant which shows that the


non-repeatable reads and dirty reads are not allowed. However, phantom reads and
can occur.
TRANSACTION_SERIALIZABLE: It is a constant which shows that the non-
repeatable reads, dirty reads as well as the phantom reads are not allowed.

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 t


ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple result
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.

import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");
Statement stmt=con.createStatement();

//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");


//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 wher
e id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected");
con.close();
}}

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
the current position.

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

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

4) public boolean last(): is used to move the cursor to the last row in result
set object.
5) public boolean absolute(int is used to move the cursor to the specified row
row): number in the ResultSet object.

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

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

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

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

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

Example of Scrollable ResultSet

Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.

import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Result
Set.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
//getting the record of 3rd row
rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}}

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.

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 value) sets the integer value to the given parameter ind

public void setString(int paramIndex, String sets the String value to the given parameter inde
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 ind
double value)

public int executeUpdate() executes the query. It is used for create, d


update, delete etc.

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


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:

import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");

PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");


stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");

con.close();

}catch(Exception e){ System.out.println(e);}

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

import java.sql.*;
import java.io.*;
class RS{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");

PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


do{
System.out.println("enter id:");
int id=Integer.parseInt(br.readLine());
System.out.println("enter name:");
String name=br.readLine();
System.out.println("enter salary:");
float salary=Float.parseFloat(br.readLine());

ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.println(i+" records affected");

System.out.println("Do you want to continue: y/n");


String s=br.readLine();
if(s.startsWith("n")){
break;
}
}while(true);

con.close();
}}

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 colu


ResultSet object.

public String getColumnName(int index)throws it returns the column name of th


SQLException column index.

public String getColumnTypeName(int index)throws it returns the column type nam


SQLException specified index.

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

How to get the object of ResultSetMetaData:

The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Synta
1. public ResultSetMetaData getMetaData()throws SQLException

Example of ResultSetMetaData interface :

import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement("select * from emp");


ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName
(1));

con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER

You might also like