06 Java Database Connectivity

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 179

JAVA ENTERPRISE EDITION

PROGRAMMING
SUBJECT DESCRIPTION: JAVA ENTERPRISE EDITION PROGRAMMING
SUBJECT CODE: CS220

ENGR. RUELLA YARES MAGTAAS, CPE


JAVA JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect
and execute the query with the database, and processing the results. 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:

JDBC-ODBC Bridge Driver


Native Driver
Network Protocol Driver
Thin Driver
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:

Driver interface
Connection interface
Statement interface
PreparedStatement interface
CallableStatement interface
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface
A list of popular classes of JDBC API are given below:

DriverManager class
Blob class
Clob class
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 that 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:

Connect to the database


Execute queries and update statements to the database
Retrieve the result received from the database.
WHAT IS API?

JDBC also provides support for handling database metadata that allows us to
retrieve information about the database, such as its tables, columns, and indexes.
We can use the DatabaseMetaData interface to obtain this information that can be
useful for dynamically generating SQL queries or for database schema
introspection.

Another important feature of JDBC is its support for batch processing that allows
us to group multiple SQL statements into a batch and execute them together. It
can improve performance by reducing the number of round trips between the
application and the database.
JDBC DRIVER
JDBC DRIVER

JDBC Driver is a software component that enables java


application to interact with the database. There are 4 types of
JDBC drivers:
JDBC-ODBC bridge driver
Native-API driver (partially java driver)
Network Protocol driver (fully java driver)
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.
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:
easy to use.
can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the
ODBC function calls.
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:
performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
The Native driver needs to be installed on the each client machine.
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:
No client side library is required because of application server that can
perform many tasks like auditing, load balancing, logging etc.
Disadvantages:
Network support is required on client machine.
Requires database-specific coding to be done in the middle tier.
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:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.
JAVA DATABASE CONNECTIVITY WITH 5
STEPS
There are 5 steps to connect any
java application with the database
using JDBC. These steps are as
follows:
Register the Driver class
Create connection
Create statement
Execute queries
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 dynamically load the driver
class.
Syntax of forName() method
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
EXAMPLE TO REGISTER THE
ORACLEDRIVER CLASS

Here, Java program is loading oracle driver to esteblish


database connection.

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) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String
password)
throws SQLException
EXAMPLE TO ESTABLISH CONNECTION
WITH THE ORACLE DATABASE

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
public Statement createStatement()throws SQLException
EXAMPLE TO CREATE THE STATEMENT
OBJECT

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
public ResultSet executeQuery(String sql)throws SQLException
EXAMPLE TO EXECUTE QUERY

ResultSet rs=stmt.executeQuery("select * from emp");


while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
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
public void close()throws SQLException
EXAMPLE TO CLOSE CONNECTION

con.close();
JAVA DATABASE CONNECTIVITY WITH
ORACLE
JAVA DATABASE CONNECTIVITY WITH
ORACLE
To connect java application with the oracle database, we need to follow 5 following
steps. In this example, we are using Oracle 10g as the database. So we need to
know following information for the oracle database:
Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
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.
Username: The default username for the oracle database is system.
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 SQL query to create a table.
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);}

}
}
To connect java application with the Oracle database
ojdbc14.jar file is required to be loaded.
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:


temporary
permanent
HOW TO SET THE TEMPORARY
CLASSPATH:

Firstly, search the ojdbc14.jar file then open command prompt


and write:
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;.;
JAVA 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.
create database sonoo;
use sonoo;
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);}
}
}
To connect java application with the mysql database,
mysqlconnector.jar file is required to be loaded.
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:


temporary
permanent
HOW TO SET THE TEMPORARY CLASSPATH

open command prompt and write:


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;.;
CONNECTIVITY WITH ACCESS WITHOUT
DSN
There are two ways to connect java application with the access
database.
1.Without DSN (Data Source Name)
2.With DSN
Java is mostly used with Oracle, mysql, or DB2 database.
EXAMPLE TO CONNECT JAVA APPLICATION
WITH ACCESS WITHOUT DSN

In this example, we are going to connect the java program with


the access database. In such case, we have created the login
table in the access database. There is only one column in the
table named name. Let's get all the name of the login table.
import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String database="student.mdb";//
Here database exists in the current directory

String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}


;
DBQ=" + database + ";DriverID=22;READONLY=tru
e";

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");

while(rs.next()){
System.out.println(rs.getString(1));
}

}catch(Exception ee){System.out.println(ee);}
EXAMPLE TO CONNECT JAVA APPLICATION
WITH ACCESS WITH DSN

Connectivity with type1 driver is not considered good. To


connect java application with type1 driver, create DSN first,
here we are assuming your dsn name is mydsn.
import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String url="jdbc:odbc:mydsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");

while(rs.next()){
System.out.println(rs.getString(1));
}

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

}}
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
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 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.
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=1
0000 where 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:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,

ResultSet.CONCUR_UPDATABLE);
COMMONLY USED METHODS OF
RESULTSET INTERFACE
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:x
e","system","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSe
t.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
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:
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:
public PreparedStatement prepareStatement(String query)throws SQLException{}
METHODS OF PREPAREDSTATEMENT
INTERFACE
The important methods of PreparedStatement interface are given below:
EXAMPLE OF PREPAREDSTATEMENT
INTERFACE THAT INSERTS THE RECORD

First of all create table as given below:


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

}
EXAMPLE OF PREPAREDSTATEMENT
INTERFACE THAT UPDATES THE RECORD
PreparedStatement stmt=con.prepareStatement("update emp set name=? whe
re id=?");

stmt.setString(1,"Sonoo");//
1 specifies the first parameter in the query i.e. name

stmt.setInt(2,101);

int i=stmt.executeUpdate();

System.out.println(i+" records updated");


EXAMPLE OF PREPAREDSTATEMENT
INTERFACE THAT DELETES THE RECORD

PreparedStatement stmt=con.prepareStatement("delete from


emp where id=?");

stmt.setInt(1,101);

int i=stmt.executeUpdate();

System.out.println(i+" records deleted");


EXAMPLE OF PREPAREDSTATEMENT
INTERFACE THAT RETRIEVE THE RECORDS
OF A TABLE
PreparedStatement stmt=con.prepareStatement("select * from
emp");

ResultSet rs=stmt.executeQuery();

while(rs.next()){

System.out.println(rs.getInt(1)+" "+rs.getString(2));

}
EXAMPLE OF PREPAREDSTATEMENT TO
INSERT RECORDS UNTIL USER PRESS N
import java.sql.*; float salary=Float.parseFloat(br.readLine());
import java.io.*;
class RS{ ps.setInt(1,id);
public static void main(String args[])throws Exception{ ps.setString(2,name);
Class.forName("oracle.jdbc.driver.OracleDriver"); ps.setFloat(3,salary);
Connection con=DriverManager.getConnection("jdbc:oracle:thin: int i=ps.executeUpdate();
@localhost:1521:xe","system","oracle");
System.out.println(i+" records affected");

PreparedStatement ps=con.prepareStatement("insert into emp1


System.out.println("Do you want to continue: y/n");
30 values(?,?,?)");
String s=br.readLine();
if(s.startsWith("n")){
BufferedReader br=new BufferedReader(new InputStreamRead
er(System.in)); break;
}
do{ }while(true);
System.out.println("enter id:");
int id=Integer.parseInt(br.readLine()); con.close();
System.out.println("enter name:"); }}
String name=br.readLine();
System.out.println("enter salary:");
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
HOW TO GET THE OBJECT OF
RESULTSETMETADATA:

The getMetaData() method of ResultSet interface returns the


object of ResultSetMetaData. Syntax:
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.getColumnTypeNam
e(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
JAVA DATABASEMETADATA INTERFACE
DatabaseMetaData interface provides methods to get meta
data of a database such as database product name, database
product version, driver name, name of total number of tables,
name of total number of views etc.
COMMONLY USED METHODS OF
DATABASEMETADATA INTERFACE
• public String getDriverName()throws SQLException: it returns the name of the JDBC driver.
• public String getDriverVersion()throws SQLException: it returns the version number of the JDBC
driver.
• public String getUserName()throws SQLException: it returns the username of the database.
• public String getDatabaseProductName()throws SQLException: it returns the product name of
the database.
• public String getDatabaseProductVersion()throws SQLException: it returns the product version
of the database.
• public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern,
String[] types)throws SQLException: it returns the description of the tables of the specified
catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
HOW TO GET THE OBJECT OF
DATABASEMETADATA:

The getMetaData() method of Connection interface returns the


object of DatabaseMetaData. Syntax:
public DatabaseMetaData getMetaData()throws SQLExceptio
n
SIMPLE EXAMPLE OF DATABASEMETADATA
INTERFACE :
import java.sql.*;
class Dbmd{
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");
DatabaseMetaData dbmd=con.getMetaData();

System.out.println("Driver Name: "+dbmd.getDriverName());


System.out.println("Driver Version: "+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName());
System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());

con.close();
}catch(Exception e){ System.out.println(e);}
}
}
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
EXAMPLE OF DATABASEMETADATA
INTERFACE THAT PRINTS TOTAL NUMBER
OF TABLES :
import java.sql.*;
class Dbmd2{
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");

DatabaseMetaData dbmd=con.getMetaData();
String table[]={"TABLE"};
ResultSet rs=dbmd.getTables(null,null,null,table);

while(rs.next()){
System.out.println(rs.getString(3));
}

con.close();

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

}
}
EXAMPLE OF DATABASEMETADATA
INTERFACE THAT PRINTS TOTAL NUMBER
OF VIEWS :
import java.sql.*;
class Dbmd3{
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");

DatabaseMetaData dbmd=con.getMetaData();
String table[]={"VIEW"};
ResultSet rs=dbmd.getTables(null,null,null,table);

while(rs.next()){
System.out.println(rs.getString(3));
}

con.close();

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

}
}
EXAMPLE TO STORE IMAGE IN ORACLE
DATABASE
You can store images in the database in java by the help
of PreparedStatement interface.
The setBinaryStream() method of PreparedStatement is
used to set Binary information into the parameterIndex.
SIGNATURE OF SETBINARYSTREAM
METHOD

The syntax of setBinaryStream() method is given below:


1) public void setBinaryStream(int paramIndex,InputStream stream)

throws SQLException

2) public void setBinaryStream(int paramIndex,InputStream stream,long length)

throws SQLException
For storing image into the database, BLOB (Binary Large Object) datatype is used in the table. For example:
CREATE TABLE "IMGTABLE"

( "NAME" VARCHAR2(4000),

"PHOTO" BLOB

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.
JAVA EXAMPLE TO STORE IMAGE IN THE
DATABASE
import java.sql.*;
import java.io.*;
public class InsertImage {
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("insert into imgtab


le values(?,?)");
ps.setString(1,"sonoo");

FileInputStream fin=new FileInputStream("d:\\g.jpg");


ps.setBinaryStream(2,fin,fin.available());
int i=ps.executeUpdate();
System.out.println(i+" records affected");

con.close();
}catch (Exception e) {e.printStackTrace();}
}
}
EXAMPLE TO RETRIEVE IMAGE FROM
ORACLE DATABASE
By the help of PreparedStatement we can retrieve and store the
image in the database.
The getBlob() method of PreparedStatement is used to get Binary
information, it returns the instance of Blob. After calling
the getBytes() method on the blob object, we can get the array of
binary information that can be written into the image file.
SIGNATURE OF GETBLOB() METHOD OF
PREPAREDSTATEMENT

public Blob getBlob()throws SQLException


SIGNATURE OF GETBYTES() METHOD OF
BLOB INTERFACE
public byte[] getBytes(long pos, int length)throws SQLException
We are assuming that image is stored in the imgtable.
CREATE TABLE "IMGTABLE"

( "NAME" VARCHAR2(4000),

"PHOTO" BLOB

/
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.
import java.sql.*;
import java.io.*;
public class RetrieveImage {
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 imgtable");


ResultSet rs=ps.executeQuery();
if(rs.next()){//now on 1st row

Blob b=rs.getBlob(2);//2 means 2nd column data


byte barr[]=b.getBytes(1,(int)b.length());//1 means first image

FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");


fout.write(barr);

fout.close();
}//end of if
System.out.println("ok");

con.close();
}catch (Exception e) {e.printStackTrace(); }
}
}
EXAMPLE TO STORE FILE IN ORACLE
DATABASE:
The setCharacterStream() method of PreparedStatement is
used to set character information into the parameterIndex.
Syntax:
1) public void setBinaryStream(int paramIndex,InputStream
stream)throws SQLException
2) public void setBinaryStream(int paramIndex,InputStream
stream,long length)throws SQLException
For storing file into the database, CLOB (Character Large Object) datatype is used in the
table. For example:
CREATE TABLE "FILETABLE"

( "ID" NUMBER,

"NAME" CLOB

/
JAVA EXAMPLE TO STORE FILE IN
DATABASE
import java.io.*;
import java.sql.*;

public class StoreFile {


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(
"insert into filetable values(?,?)");

File f=new File("d:\\myfile.txt");


FileReader fr=new FileReader(f);

ps.setInt(1,101);
ps.setCharacterStream(2,fr,(int)f.length());
int i=ps.executeUpdate();
System.out.println(i+" records affected");

con.close();

}catch (Exception e) {e.printStackTrace();}


}
}
EXAMPLE TO RETRIEVE FILE FROM
ORACLE DATABASE:
The getClob() method of PreparedStatement is used to get file
information from the database.
SYNTAX OF GETCLOB METHOD

public Clob getClob(int columnIndex){}


Let's see the table structure of this example to retrieve the file.
CREATE TABLE "FILETABLE"

( "ID" NUMBER,

"NAME" CLOB

/
The example to retrieve the file from the Oracle database is given below.
import java.io.*;
import java.sql.*;

public class RetrieveFile {


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


ResultSet rs=ps.executeQuery();
rs.next();//now on 1st row

Clob c=rs.getClob(2);
Reader r=c.getCharacterStream();

FileWriter fw=new FileWriter("d:\\retrivefile.txt");

int i;
while((i=r.read())!=-1)
fw.write((char)i);

fw.close();
con.close();

System.out.println("success");
}catch (Exception e) {e.printStackTrace(); }
}
}
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:
HOW TO GET THE INSTANCE OF
CALLABLESTATEMENT?
The prepareCall() method of Connection interface returns the instance of
CallableStatement. Syntax is given below:
public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

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


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.

create or replace procedure "INSERTR"

(id IN NUMBER,

name IN VARCHAR2)

is

begin

insert into user420 values(id,name);

end;

/
The table structure is given below:
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
import java.sql.*;
public class Proc {
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");

CallableStatement stmt=con.prepareCall("{call insertR(?,


?)}");
stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();

System.out.println("success");
}
}
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.

create or replace function sum4


(n1 in number,n2 in number)
return number
is
temp number(8);
begin
temp :=n1+n2;
return temp;
end;
/
Now, let's write the simple program to call the
function. import java.sql.*;

public class FuncSum {


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

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


stmt.setInt(2,10);
stmt.setInt(3,43);
stmt.registerOutParameter(1,Types.INTEGER);
stmt.execute();

System.out.println(stmt.getInt(1));

}
}
TRANSACTION MANAGEMENT IN JDBC
Transaction represents a single unit of work.
The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to another consistent state.
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the event of
errors, power loss etc.
ADVANTAGE OF TRANSACTION
MANAGEMENT

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.
SIMPLE EXAMPLE OF TRANSACTION
MANAGEMENT IN JDBC USING STATEMENT
import java.sql.*;
class FetchRecords{
public static void main(String args[])throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:orac
le:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);

Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi
',40000)");
stmt.executeUpdate("insert into user420 values(191,'ume
If you see the
table emp400, sh',50000)");
you will see that
2 records has con.commit();
been added.
con.close();
}}
EXAMPLE OF TRANSACTION
MANAGEMENT IN JDBC USING
PREPAREDSTATEMENT
import java.sql.*; ps.setInt(3,salary);
import java.io.*; ps.executeUpdate();
class TM{
public static void main(String args[]){ System.out.println("commit/rollback");
try{ String answer=br.readLine();
if(answer.equals("commit")){
Class.forName("oracle.jdbc.driver.OracleDriver"); con.commit();
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localho }
st:1521:xe","system","oracle"); if(answer.equals("rollback")){
con.setAutoCommit(false); con.rollback();
}
PreparedStatement ps=con.prepareStatement("insert into user420 values
(?,?,?)");
System.out.println("Want to add more records y/n");
BufferedReader br=new BufferedReader(new InputStreamReader(System String ans=br.readLine();
.in)); if(ans.equals("n")){
while(true){ break;
}
System.out.println("enter id");
String s1=br.readLine(); }
int id=Integer.parseInt(s1); con.commit();
System.out.println("record successfully saved");
System.out.println("enter name");
String name=br.readLine(); con.close();//before closing connection commit() is called
}catch(Exception e){System.out.println(e);}
System.out.println("enter salary");
String s3=br.readLine(); }}
int salary=Integer.parseInt(s3);

ps.setInt(1,id);
BATCH PROCESSING IN JDBC
Instead of executing a single query, we can execute a batch (group) of
queries. It makes the performance fast. It is because when one sends
multiple statements of SQL at once to the database, the communication
overhead is reduced significantly, as one is not communicating with the
database frequently, which in turn results to fast performance.
The java.sql.Statement and java.sql.PreparedStatement interfaces provide
methods for batch processing.
ADVANTAGE OF BATCH PROCESSING

Fast Performance
METHODS OF STATEMENT INTERFACE
EXAMPLE OF BATCH PROCESSING IN JDBC

Let's see the simple example of batch processing in JDBC. It follows following
steps:
Load the driver class
Create Connection
Create Statement
Add query in the batch
Execute Batch
Close Connection
EXAMPLE OF BATCH PROCESSING USING
PREPAREDSTATEMENT
import java.sql.*; String s3=br.readLine();
import java.io.*; int salary=Integer.parseInt(s3);
class BP{
public static void main(String args[]){ ps.setInt(1,id);
try{ ps.setString(2,name);
ps.setInt(3,salary);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle: ps.addBatch();
thin:@localhost:1521:xe","system","oracle"); System.out.println("Want to add more records y/n");
String ans=br.readLine();
PreparedStatement ps=con.prepareStatement("insert into u if(ans.equals("n")){
ser420 values(?,?,?)"); break;
}
BufferedReader br=new BufferedReader(new InputStreamR }
eader(System.in)); ps.executeBatch();// for executing the batch
while(true){
System.out.println("record successfully saved");
System.out.println("enter id");
String s1=br.readLine(); con.close();
int id=Integer.parseInt(s1); }catch(Exception e){System.out.println(e);}

System.out.println("enter name"); }}
String name=br.readLine();

System.out.println("enter salary");
OUTPUT:

enter id 103
101 enter name
enter name Rohit Anuragi
Manoj Kumar enter salary
enter salary 30000
10000 Want to add more records y/n
Want to add more records y/n y
y enter id
enter id 104
101 enter name
enter name Amrit Gautam
Harish Singh enter salary
enter salary 40000
15000 Want to add more records y/n
Want to add more records y/n n
y record successfully saved
enter id
JDBC ROWSET
An instance of RowSet is the Java bean component because it has properties and Java bean
notification mechanism. It is the wrapper of ResultSet. A JDBC RowSet facilitates a mechanism to keep
the data in tabular form. It happens to make the data more flexible as well as easier as compared to a
ResultSet. The connection between the data source and the RowSet object is maintained throughout
its life cycle. The RowSet supports development models that are component-based such as JavaBeans,
with the standard set of properties and the mechanism of event notification.
It was in the JDBC 2.0, the support for the RowSet was introduced using the optional packages. But the
implementations were standardized for RowSet in the JDBC RowSet Implementations Specification (JSR-
114) by the Sun Microsystems that is being present in the JDK (Java Development Kit) 5.0.
The implementation classes of the
RowSet interface are as follows:
JdbcRowSet
CachedRowSet
WebRowSet
JoinRowSet
FilteredRowSet
ADVANTAGE OF ROWSET

The advantages of using RowSet are given below:


It is easy and flexible to use.
It is Scrollable and Updatable by default.
EXAMPLE OF JDBCROWSET
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;

public class RowSetExample {


public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");

//Creating and Executing RowSet


JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
rowSet.setUsername("system");
rowSet.setPassword("oracle");

rowSet.setCommand("select * from emp400");


rowSet.execute();

while (rowSet.next()) {
// Generating cursor Moved event
System.out.println("Id: " + rowSet.getString(1));
System.out.println("Name: " + rowSet.getString(2));
System.out.println("Salary: " + rowSet.getString(3));
}

}
}
THE OUTPUT IS GIVEN BELOW:

Id: 55
Name: Om Bhim
Salary: 70000
Id: 190
Name: abhi
Salary: 40000
Id: 191
Name: umesh
Salary: 50000
EXAMPLE OF JDBC ROWSET WITH EVENT
HANDLING
To perform event handling with JdbcRowSet, you need to add the instance
of RowSetListener in the addRowSetListener method of JdbcRowSet.
The RowSetListener interface provides 3 method that must be
implemented. They are as follows:
public void cursorMoved(RowSetEvent event);
public void rowChanged(RowSetEvent event);
public void rowSetChanged(RowSetEvent event);
import java.sql.Connection; // Generating cursor Moved event
import java.sql.DriverManager; System.out.println("Id: " + rowSet.getString(1));
import java.sql.ResultSet; System.out.println("Name: " + rowSet.getString(2));
import java.sql.Statement; System.out.println("Salary: " + rowSet.getString(3));
import javax.sql.RowSetEvent; }
import javax.sql.RowSetListener;
import javax.sql.rowset.JdbcRowSet; }
import javax.sql.rowset.RowSetProvider; }

public class RowSetExample { class MyListener implements RowSetListener {


public static void main(String[] args) throws Exception { public void cursorMoved(RowSetEvent event) {
Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Cursor Moved...");
}
//Creating and Executing RowSet public void rowChanged(RowSetEvent event) {
JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet(); System.out.println("Cursor Changed...");
rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe"); }
rowSet.setUsername("system"); public void rowSetChanged(RowSetEvent event) {
rowSet.setPassword("oracle"); System.out.println("RowSet changed...");
}
rowSet.setCommand("select * from emp400"); }
rowSet.execute();

//Adding Listener and moving RowSet


rowSet.addRowSetListener(new MyListener());

while (rowSet.next()) {
THE OUTPUT IS AS FOLLOWS:

Cursor Moved...
Id: 55
Name: Om Bhim
Salary: 70000
Cursor Moved...
Id: 190
Name: abhi
Salary: 40000
Cursor Moved...
Id: 191
Name: umesh
Salary: 50000
Cursor Moved...
MULTIPLE CHOICE QUESTIONS ON JDBC IN
JAVA
JDBC is an API (Application Programming Interface) that helps a programmer
to write a Java program to connect to a database, retrieve the data from the
database, and perform various operations on the data in a Java program.
As it is an important topic, the questions related to JDBC frequently asked in
Java interviews and competitive exams. So, in this section, we have collected
some multiple-choice questions based on JDBC that are important from
the perspective of different competitive exams and interviews.
WHAT ARE THE MAJOR COMPONENTS OF
THE JDBC?
DriverManager: Manages a list of database drivers.
Driver: The database communications link, handling all communication
with the database.
Connection: Interface with all methods for contacting a database.
Statement: Encapsulates an SQL statement which is passed to the
database to be parsed, compiled, planned, and executed.
ResultSet: The ResultSet represents a set of rows retrieved due to
query execution.
PACKAGES IN WHICH JDBC CLASSES ARE
DEFINED?

JDBC API is divided into two packages i.e. java.sql and


javax.sql. We have to import these packages to use classes
and interfaces in our application.
THIN DRIVER IS ALSO KNOWN AS?

The JDBC thin driver is a pure Java driver. It is also known as


Type-4 Driver. It is platform-independent so it does not require
any additional Oracle software on the client-side. It
communicates with the server using SQL *Net to access Oracle
Database.
CORRECT SEQUENCE TO CREATE A
DATABASE CONNECTION
• To create a database connection in Java, we must follow the sequence given below:
1. Import JDBC packages.
2. Load and register the JDBC driver.
3. Open a connection to the database.
4. Create a statement object to perform a query.
5. Execute the statement object and return a query resultset.
6. Process the resultset.
7. Close the resultset and statement objects.
8. Close the connection.
METHOD USED TO PERFORM DML
STATEMENTS IN JDBC

We use the executeUpdate() method for DML SQL queries that


change data in the database, such as INSERT, UPDATE, and
DELETE which do not return a resultset.
TRANSACTION ISOLATION LEVELS PROVIDE
THE JDBC THROUGH THE CONNECTION
INTERFACE
METHOD IS STATIC AND SYNCHRONIZED IN
JDBC API

A Java application using the JDBC API establishes a connection


to a database by obtaining a Connection object. The standard
way to obtain a Connection object is to call the method
DriverManager.getConnection() method that accepts a String
contains the database connection URL. It is a static and
synchronized method.
METHODS REQUIRED TO LOAD A
DATABASE DRIVER IN JDBC
• There are two ways to load a database driver in JDBC:
• By using the registerDriver() Method: To access the database through a Java
application, we must register the installed driver in our program. We can do this
with the registerDriver() method that belongs to the DriverManager class. The
registerDriver() method takes as input a driver class, that is, a class that
implements the java.sql.Driver interface, as is the case with OracleDriver.
• By using the Class.forName() Method: Alternatively, we can also use the
forName() method of the java.lang.Class to load the JDBC drivers directly.
However, this method is valid only for JDK-compliant Java virtual machines. It is
invalid for Microsoft JVMs.
PARAMETERIZED QUERIES

The PreparedStatement interface extends the Statement


interface. It represents a precompiled SQL statement that can
be executed multiple times. It accepts parameterized SQL
quires. We can pass 0 or more parameters to this query.
NOT A VALID STATEMENT IN JDBC

Statement: Use this for general-purpose access to your


database. It is useful when we are using static SQL statements
at runtime. The Statement interface cannot accept parameters.
PreparedStatement: It represents the pre-compiled SQL
statements that can be executed multiple times.
CallableStatement: It is used to execute SQL stored procedures.
QueryStatement: It is not supported by JDBC.
ISOLATION LEVEL THAT PREVENTS THE
DIRTY IN THE JDBC CONNECTION CLASS

The isolation level TRANSACTION_READ_COMMITTED prevents


the dirty read but non-repeatable reads and phantom reads
can occur.
SETAUTOCOMMIT(FALSE)

The way to allow two or more statements to be grouped into a


transaction is to disable the auto-commit mode. After the auto-
commit mode is disabled, no SQL statements are committed
until we call the commit() method explicitly.
STORED PROCEDURE CAN BE CALLED BY

The stored procedure is a database program that can be


utilized to perform CRUD tasks with the table. We can call
these procedures by using the Statement Interface. It provides
methods to execute queries with the database.
JDBC-ODBC DRIVER IS ALSO KNOWN AS

Type 1 driver is also known as the JDBC-ODBC bridge driver. It


is a database driver implementation that employs the ODBC
driver to connect to the database. The driver converts JDBC
method calls into ODBC function calls.
FASTEST DRIVER

JDBC Net pure Java driver (Type 4) is the fastest driver because
it converts the JDBC calls into vendor-specific protocol calls and
it directly interacts with the database.
THREE TYPES OF RESULTSET OBJECT

• TYPE_FORWARD_ONLY: This is the default type and the cursor can only move
forward in the result set.
• TYPE_SCROLL_INSENSITIVE: The cursor can move forward and backward, and
the result set is not sensitive to changes made by others to the database after the
result set was created.
• TYPE_SCROLL_SENSITIVE: The cursor can move forward and backward, and the
result set is sensitive to changes made by others to the database after the result
set was created.
BASED ON THE CONCURRENCY THERE
ARE TWO TYPES OF RESULTSET OBJECT.

CONCUR_READ_ONLY: The ResultSet is read-only, this is the


default concurrency type.
CONCUR_UPDATABLE: We can use the ResultSet update
method to update the rows data.
JDBC SAVEPOINT

JDBC Savepoint helps us in creating checkpoints in a


transaction and we can rollback to that particular checkpoint.
FOLLOWING STAGES IN A JDBC PROGRAM

Register the driver


Connecting to a database
Preparing SQL statements in Java
Executing the SQL statements on the database
Retrieving the results
Closing the connection

You might also like