0% found this document useful (0 votes)
6 views

JDBC

The document provides an overview of database connectivity in Java, focusing on the JDBC API, which allows Java applications to connect and execute queries with databases. It explains the history of database connectivity, the types of JDBC drivers, and the advantages and disadvantages of each driver type. Additionally, the document outlines the steps to connect to a database using JDBC, including registering the driver, creating a connection, executing queries, and closing the connection.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

JDBC

The document provides an overview of database connectivity in Java, focusing on the JDBC API, which allows Java applications to connect and execute queries with databases. It explains the history of database connectivity, the types of JDBC drivers, and the advantages and disadvantages of each driver type. Additionally, the document outlines the steps to connect to a database using JDBC, including registering the driver, creating a connection, executing queries, and closing the connection.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 70

DATABASE

CONNECTIVITY

1
Java and the database

 Database is used to store data. It is also known as


persistent storage as the data is stored and can be
retrieved anytime.
 Java and database are used almost everywhere to
store persistent data and retrieve it when required.
SQL

 Information stored in the database is in tables and


the language used to query information from the
database is SQL.
 Using SQL we can query a table based on the
requirement.
Database Connectivity History

Before APIs like JDBC and ODBC, database connectivity was


tedious
Each database vendor provided a function library for
accessing their database
The connectivity library was proprietary.
If the database vendor changed for the application, the data
access portions had to be rewritten
If the application was poorly structured, rewriting its data
access might involve rewriting the majority of the
application
The costs incurred generally meant that application
developers were stuck with a particular database product for
a given application
Java JDBC

Java JDBC is a java API to connect and execute query with


the database. JDBC API uses jdbc drivers to connect with the
database.

5
Why use JDBC

Before JDBC, ODBC API was the database API


to connect and execute query with the database.
But, ODBC API uses ODBC driver which is
written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own
API (JDBC API) that uses JDBC drivers (written
in Java language).

6
What is API

API (Application programming interface) is a


document that contains description of all the
features of a product or software. It represents
classes and interfaces that software programs can
follow to communicate with each other. An API
can be created for applications, libraries,
operating systems, etc

7
What is the JDBC API?
 A set of classes and interfaces written in the Java
 a standard API for tool/database developers &
 makes possible to write database applications using an Java API.
 Obtaining a variety of different data sources is possible
for Java applications
 Makes possible to publish a web page containing an
applet that uses information obtained from a remote data
source. For example:
 To connect all employees (even if they are using Windows, Macintosh,
and UNIX machines) is possible as one or more internal databases via an
intranet
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)

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

10
Java application
JDBC API

JDBC Driver Manager


JDBC Driver API
vendor-
JDBC/ODBC
supplied
Bridge
JDBC driver

ODBC
driver

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

12
Why not Use ODBC from Java?
 Before the development of the JDBC API
 The most widely used programming interface Microsoft's ODBC (Open
DataBase Connectivity) API
 To access relational databases
 ODBC can be used with Java, but
 The best application is JDBC API
 Applied as the form of the JDBC-ODBC Bridge

 ODBC is not appropriate for direct use from the Java programming
language
 Uses C interface.
 Occurs a number of drawbacks in the security, implementation, robustness,
automatic portability
 during the calls from Java to native C code
QUESTION:
What are other important differences between JDBC API and ODBC API?

 Once ODBC (as native code) is called, Java programming language can't guarantee
that a security violation won't occur (untrusted).
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.

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

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

16
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.
17
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.

18
Advantage:
 Better performance than all other drivers.
 No software is required at client side or server side.

Disadvantage:
 Drivers depends on the Database.

19
Type 1 3rd Party API

Database
Type 3 Type 2 Native C/C++ API

Local API
Network API
Type 4
• Type 1: Uses a bridging technology to access a database. JDBC-ODBC
bridge is an example. It provides a gateway to the ODBC.
• Type 2: Native API drivers. Driver contains Java code that calls native C/C++

methods provided by the database vendors.


• Type 3: Generic network API that is then translated into database-specific

access at the server level. The JDBC driver on the client uses sockets to call a
middleware application on the server that translates the client requests into an
API specific to the desired driver. Extremely flexible.
• Type 4: Using network protocols built into the database engine talk directly to

the database using Java sockets. Almost always comes only from database
vendors.
Java Application

JDBC driver manager

JDBC/native JDBC/ODBC JDBC Driver JDBC middleware


bridge bridge (DBMS Specific) (various DBMS)

Native driver
ODBC Driver
(DBMS specific)

DBMS
JDBC- to ODBC driver (Type 1)

 A good approach for learning JDBC. May be useful for


companies that already have ODBC drivers installed on
each client machine
 The case for Windows-based machines running productivity applications.
 May be the only way to gain access to some low-end desktop databases.

 Not for large-scale applications. Performance suffers


because there's some overhead associated with the
translation work to go from JDBC to ODBC. Doesn't
support all the features of Java. User is limited by the
functionality of the underlying ODBC driver
Native-API, partly driver (Type 2)
 Converts the calls that a developer writes to the JDBC application
programming interface into calls that connect to the client machine's
application programming interface for a specific database, such as
IBM, Informix, Oracle or Sybase.

 Performance is better than that of Type 1, in part because the Type 2


driver contains compiled code that's optimized for the back-end
database server's operating system.
 User needs to make sure the JDBC driver of the database vendor is
loaded onto each client machine. Must have compiled code for every
operating system that the application will run on. Best use is for
controlled environments, such as an intranet.
JDBC- Net pure driver (Type 3)
 Pure Java driver for database middleware, which provides connectivity to many
different databases.

 Translates JDBC calls into the middleware vendor's protocol, which is then
converted to a database-specific protocol by the middleware server software.
 Better performance than Types 1 and 2. Can be used when a company has multiple
databases and wants to use a single JDBC driver to connect to all of them.

 Server-based, so no need for JDBC driver code on client machine.


 For performance reasons, the back-end server component is optimized for the
operating system that the database is running on.

 Needs some database-specific code on the middleware server. If the middleware


must run on different platforms, a Type 4 driver might be more effective.
Native-Protocol pure (all) Java driver (Type 4)

 Written entirely in Java

 Converts JDBC calls into packets


 that are sent over the network in the proprietary format
 used by the specific database.

 Allows a direct call from the client machine to the database.


 Better performance than Types 1 and 2.

 No need to install special software on client or server. Can be


downloaded dynamically.

.
5 Steps to connect to the
database in java
There are 5 steps to connect any java application
with the database in java using JDBC. They are as
follows:
 Register the driver class
 Creating connection
 Creating statement
 Executing queries
 Closing connection

26
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 ClassNot
FoundException

Example to register the OracleDriver class


 Class.forName("oracle.jdbc.driver.OracleDriver");
27
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 pass
word) throws SQLException

Example to establish connection with the Oracle database


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

28
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 SQLExce
ption

Example to create the statement object


 Statement stmt=con.createStatement();
29
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));
}

30
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();
31
Example to connect to the Oracle
database in java
For connecting java application with the oracle database, you need to follow 5
steps to perform database connectivity. In this example we are using
Oracle10g as the database. So we need to know following information for the
oracle database:
 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: Password is given by the user at the time of installing the oracle
database.
32
Example to Connect Java Application with 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);}


 }
 }

33
Example to connect to the mysql
database
For connecting in
java java
application with the mysql database, you need to
follow 5 steps to perform database connectivity. In this example we are
using MySql as the database. So we need to know following informations
for the mysql database:

 Driver class: The driver class for the mysql database


is com.mysql.jdbc.Driver.
 Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the
database, localhost is the server name on which mysql is running, we may
also use IP address, 3306 is the port number and sonoo is the database
name. We may use any database, in such case, you need to replace the
sonoo with your database name.
 Username: The default username for the mysql database is root.
 Password: Password is given by the user at the time of installing the
mysql database. In this example, we are going to use root as the password.
34
Example to Connect Java Application with mysql
database
 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);}
 }
 }
35
Create Query
 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/snow?
useSSL=true","root","root");
 //here sonoo is database name, root is username and password
 Statement stmt=con.createStatement();
 stmt.executeUpdate("create table stud(name varchar(255), id int)");
 //while(rs.next())
 //System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
 con.close();
 }catch(Exception e){ System.out.println(e);}
 }
 }

36
Insert data to database-
Insert Query
 import java.awt.*;
 import java.awt.event.*;
 import java.sql.*;

 class formcon extends Frame implements ActionListener{


 TextField t1,t2;
 Label l1,l2,l3;

 formcon(){
 //create components
 l1=new Label("id",Label.RIGHT);
 l1.setBounds(30,50,70,30);

 t1=new TextField();
 t1.setBounds(120,50,150,30);

 l2=new Label("name",Label.RIGHT);
 l2.setBounds(30,100,70,30);

 t2=new TextField();
 t2.setBounds(120,100,150,30);

 l3=new Label();
 l3.setBounds(120,190,150,30);
 l3.setBackground(Color.LIGHT_GRAY);

 Button b=new Button("click me");


 b.setBounds(150,250,80,30);

 //register listener
 b.addActionListener(this);//passing current instance
 37
 //add components and set size, layout and visibility
 add(b);add(l1);add(t1);add(l2);add(t2);add(l3);
 setSize(400,400);
 setLayout(null);
 setVisible(true);
 }
 public void actionPerformed(ActionEvent e){

 try
 {
 Class.forName("com.mysql.jdbc.Driver");

 // Create connection
 Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/snow?useSSL=true","root","root");

 int id=Integer.parseInt(t1.getText());
 String n=t2.getText();

 Statement stmt=conn.createStatement();
 stmt.executeUpdate("INSERT INTO stud values('"+n+"','"+id+"')");
 l3.setText("Insert Successfully");

 }
 catch(Exception x){}
 }
 public static void main(String args[]){
 new formcon();
 } }

38
Update query
 import java.sql.*;

 public class JDBCExample {


 // JDBC driver name and database URL
 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
 static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

 // Database credentials
 static final String USER = "username";
 static final String PASS = "password";

 public static void main(String[] args) {


 Connection conn = null;
 Statement stmt = null;
 try{
 //STEP 2: Register JDBC driver
 Class.forName("com.mysql.jdbc.Driver");

 //STEP 3: Open a connection


 System.out.println("Connecting to a selected database...");
 conn = DriverManager.getConnection(DB_URL, USER, PASS);
 System.out.println("Connected database successfully...");

 //STEP 4: Execute a query


 System.out.println("Creating statement...");
 stmt = conn.createStatement();
 String sql = "UPDATE Registration " +
 "SET age = 30 WHERE id in (100, 101)";
39
Update query contd….
 stmt.executeUpdate(sql);

 // Now you can extract all the records


 // to see the updated records
 sql = "SELECT id, first, last, age FROM Registration";
 ResultSet rs = stmt.executeQuery(sql);

 while(rs.next()){
 //Retrieve by column name
 int id = rs.getInt("id");
 int age = rs.getInt("age");
 String first = rs.getString("first");
 String last = rs.getString("last");

 //Display values
 System.out.print("ID: " + id);
 System.out.print(", Age: " + age);
 System.out.print(", First: " + first);
 System.out.println(", Last: " + last);
 }
 rs.close();
 }catch(SQLException se){
 //Handle errors for JDBC
 se.printStackTrace();
 }

40
Delete Query
 import java.sql.*;

 public class JDBCExample {


 // JDBC driver name and database URL
 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
 static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

 // Database credentials
 static final String USER = "username";
 static final String PASS = "password";

 public static void main(String[] args) {


 Connection conn = null;
 Statement stmt = null;
 try{
 //STEP 2: Register JDBC driver
 Class.forName("com.mysql.jdbc.Driver");

 //STEP 3: Open a connection


 System.out.println("Connecting to a selected database...");
 conn = DriverManager.getConnection(DB_URL, USER, PASS);
 System.out.println("Connected database successfully...");

 //STEP 4: Execute a query


 System.out.println("Creating statement...");
 stmt = conn.createStatement();
 String sql = "DELETE FROM Registration " +
 "WHERE id = 101";
 stmt.executeUpdate(sql);

41
Delete query contd…
 // Now you can extract all the records
 // to see the remaining records
 sql = "SELECT id, first, last, age FROM Registration";
 ResultSet rs = stmt.executeQuery(sql);

 while(rs.next()){
 //Retrieve by column name
 int id = rs.getInt("id");
 int age = rs.getInt("age");
 String first = rs.getString("first");
 String last = rs.getString("last");

 //Display values
 System.out.print("ID: " + id);
 System.out.print(", Age: " + age);
 System.out.print(", First: " + first);
 System.out.println(", Last: " + last);
 }
 rs.close();
 }catch(SQLException se){
 //Handle errors for JDBC
 se.printStackTrace();
 }

42
Connect

Query

Process
results

Close
Connect Register the driver

Query Connect to the database

Process
results

Close
Connect

Query Create a statement

Process Query the database


results

Close
Connect

Query
Step through the results

Process Assign results to Java


results variables

Close
Connect

Query
Close the result set

Process
results Close the statement

Close Close the connection


JDBC Interfaces

Driver
All JDBC Drivers must implement the Driver interface. Used to obtain a
connection to a specific database type
• Connection
Represents a connection to a specific database
Used for creating statements
Used for managing database transactions
Used for accessing stored procedures
Used for creating callable statements

Statement
Used for executing SQL statements against the database
JDBC Interfaces
ResultSet
Represents the result of an SQL statement
Provides methods for navigating through the resulting data
• PreparedStatement
Similar to a stored procedure
An SQL statement (which can contain parameters) is compiled and stored in the
database

CallableStatement
Used for executing stored procedures

DatabaseMetaData
Provides access to a database's system catalogue

ResultSetMetaData
Provides information about the data contained within a ResultSet
DBC - Statements, PreparedStatement and
CallableStatement
 Once a connection is obtained we can interact with the database. The
JDBC Statement, CallableStatement, and PreparedStatement interfaces define the
methods and properties that enable you to send SQL or PL/SQL commands and
receive data from your database.
 They also define methods that help bridge data type differences between Java and
SQL data types used in a database.
 The following table provides a summary of each interface's purpose to decide on
the interface to use.

50
The Statement Objects: Creating
Statement
 Object
Before you can use a Statement object to execute a SQL statement, you need to create one using the
Connection object's createStatement( ) method, as in the following example −
Statement stmt = null;
try {
stmt = conn.createStatement( );
...
}
catch (SQLException e)
{...
} finally
{...
}
Once you've created a Statement object, you can then use it to execute an SQL statement with one of its three
execute methods.
 boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved;
otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly
dynamic SQL.
 int executeUpdate (String SQL): Returns the number of rows affected by the execution of the SQL
statement. Use this method to execute SQL statements for which you expect to get a number of rows affected
- for example, an INSERT, UPDATE, or DELETE statement.
 ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method when you expect to get
a result set, as you would with a SELECT statement.

51
Closing Statement Object
 Just as you close a Connection object to save database
resources, for the same reason you should also close the
Statement object.
 A simple call to the close() method will do the job. If you
close the Connection object first, it will close the Statement
object as well. However, you should always explicitly close
the Statement object to ensure proper cleanup.

 stmt.close();

52
PreparedStatement interface
 The PreparedStatement interface extends the Statement interface, which gives
you added functionality with a couple of advantages over a generic Statement
object.
 This statement gives you the flexibility of supplying arguments dynamically.
 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.
 Improves performance: The performance of the application will be
faster if you use PreparedStatement interface because query is
compiled only once.

53
Methods of
PreparedStatement interface
The important methods of PreparedStatement interface are given below:

54
Example of PreparedStatement interface
that inserts the record
 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);}


 }
 }

55
Example of PreparedStatement
interface that updates the record

PreparedStatement stmt=con.prepareStatement("update emp s


et name=? where 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");

56
Example of PreparedStatement
interface that deletes the record

PreparedStatement stmt=con.prepareStatement("d
elete from emp where id=?");
stmt.setInt(1,101);

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

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

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

59
What is the difference between stored
procedures and functions

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

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

62
Example
 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");
 }
 }

63
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;
/

64
Example cont..
 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));

 }
 }

65
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 Mangaement


 fast performance It makes the performance fast because database is hit at
the time of commit.

66
In JDBC, Connection interface provides methods to manage transaction.

67
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:oracle: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,'umesh',50000)");

 con.commit();
 con.close();
 }}

68
Example of transaction management in jdbc using
PreparedStatement
 import java.sql.*;
 import java.io.*;
 class TM{
 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");
 con.setAutoCommit(false);

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


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


 while(true){

 System.out.println("enter id");
 String s1=br.readLine();
 int id=Integer.parseInt(s1);

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

 System.out.println("enter salary");

69
Example cont…
 String s3=br.readLine();
 int salary=Integer.parseInt(s3);

 ps.setInt(1,id);
 ps.setString(2,name);
 ps.setInt(3,salary);
 ps.executeUpdate();

 System.out.println("commit/rollback");
 String answer=br.readLine();
 if(answer.equals("commit")){
 con.commit();
 }
 if(answer.equals("rollback")){
 con.rollback();
 }

 System.out.println("Want to add more records y/n");


 String ans=br.readLine();
 if(ans.equals("n")){
 break;
 }

 }
 con.commit();
 System.out.println("record successfully saved");

 con.close();//before closing connection commit() is called


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

 }}

70

You might also like