SlideShare a Scribd company logo
java database connectivity for java programming
JDBC
• Java JDBC is a ja a API tr› ctinnect an‹l execute query with
the database.
• JDBC API uses jdbc drirers to connect with the database.
JDBC
API
JDBC
JDBC Dr-ivcr
l3ata Source
Server
Why use JDBC
• betore JDBC, ODBC API was the database API to connect
and cxccutc query with the database.
• But, ODBC API uses ODBC driver which is o-ritten in C
languagc (i. c. platform clcpcndcnt ancl un.sccurccl). That is
why Java has defined its own APl (JDBC APl) that uses JDBC
drirers (written in Jara language) .
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 drircr
Native—API driver (partially java driver)
Network Protocol driver (fully java driver)
Thin driver (fully java driver)
JDBC-ODBC bridge driver
When Jax-a first came out, this was a useful driver because mtist databases only
supported ODBC access but now this type of driver is recommended only ftir
experimental use or when no other alternative is available.
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.
JDBC-ODBC bridge driver
When Jax-a first came out, this was a useful driver because mtist databases only
supported ODBC access but now this type of driver is recommended only ftir
experimental use or when no other alternative is available.
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.
Native-API driver
Aclvantage:
• performance upgraded than JDBC ODBC bridge drivcr.
Disadvantage:
be installecl ‹in the each client
• The Vendor client library nccds to be installed on clicnt
machine.
Native-API driver
Aclvantage:
• performance upgraded than JDBC ODBC bridge drivcr.
Disadvantage:
be installecl ‹in the each client
• The Vendor client library nccds to be installed on clicnt
machine.
Network Protocol river
Aclvantage:
• No clicnt side librar)' is required because of application server
that can perform many tasks like auditing, load balancing,
loping etc.
Disadvantages:
• Network sugpt)rt is required ‹in client machine.
• Rcquircs databasc-specific coding to be donc in the middle tier.
• Maintenance of Network Protocol driver liecomes costl)°
because it requires database-specific cooling to be clone in the
middle tier.
Network Protocol river
Aclvantage:
• No clicnt side librar)' is required because of application server
that can perform many tasks like auditing, load balancing,
loping etc.
Disadvantages:
• Network sugpt)rt is required ‹in client machine.
• Rcquircs databasc-specific coding to be donc in the middle tier.
• Maintenance of Network Protocol driver liecomes costl)°
because it requires database-specific cooling to be clone in the
middle tier.
Network Protocol river
Aclvantage:
• No clicnt side librar)' is required because of application server
that can perform many tasks like auditing, load balancing,
loping etc.
Disadvantages:
• Network sugpt)rt is required ‹in client machine.
• Rcquircs databasc-specific coding to be donc in the middle tier.
• Maintenance of Network Protocol driver liecomes costl)°
because it requires database-specific cooling to be clone in the
middle tier.
Thin driver
Aclvantage:
• Better performance than all other drirers.
• Nti soltirare is required at client sicle or serrer sicle.
Disadvantage:
• Dripcrs depends on the Database.
Thin driver
Aclvantage:
• Better performance than all other drirers.
• Nti soltirare is required at client sicle or serrer sicle.
Disadvantage:
• Dripcrs depends on the Database.
Which Driver shou be Used?
• Native-API driver dri›ers are useful in situations, 7here
Network Protocol clriver or Thin clriver is not available
vet tor jour database.
• JDBC-ODBC bridge driver driver is not considered a
‹lepltiyment-level driver, an‹l is tygicall rused fr)r
dc›c1oprncnt ancl tcstin$ purposes only.
Which Driver shou be Used?
• Native-API driver dri›ers are useful in situations, 7here
Network Protocol clriver or Thin clriver is not available
vet tor jour database.
• JDBC-ODBC bridge driver driver is not considered a
‹lepltiyment-level driver, an‹l is tygicall rused fr)r
dc›c1oprncnt ancl tcstin$ purposes only.
Typical JDBC Programming Procedure
Loach thc databasc rhi› ‹n
Ol tain a ‹’erms rtion
Create and cxecute statt ou rite (SQL querics)
Use i ‹.hilt sets (tables) to narigate through the results
t/los‹ the connection
JDBC Programming Procedure
• Load the database driver using ClOSSLOOder :
• Class.forName(“oracle.jdbc.driver.OrocIeDriver“):
• Establish connection with the Oracle database
• connection con=DriverManager.getConnection( "jdbc:oracle:thin:
@localhost:1fi21:xe","system","password"):
• Create the statement object
• Statement stmt=con.createstatement():
• Execute the query
ResultSet rs-stmt.executeQuery("select * from emp");
while(rs.next())(
System.out.println(is.getInt(1 )+ " "+rs.getString(2));
• Close the connection
con. close();
Register DBC Driver
Approach I - Class.forName()
• The most common approach to register a driver is to use
Java's Class.forName() method
• Class.for Name("oracle.jdbc.driver.OracleDriver");
• OR
• Class.forName("oracle.jdbc.driver.OracleDriver"),newlnctance();
• Approach II - DriverManager.registerDriver()
• Driver myDriver - new oracle.jdbc. driver.OracleDriver(); DriverManager.registerDriver(
myDriver ) i
Example to connect to the Oracle database
• Driver class: driver class fOr the oracle database is
oracle.jdbc.driver.OracleDriver.
• Connection URL: The connection URL for the Oracle
database is jdbc:oracle:thin:@IP:1521:xe
• Where, IS21 is the port number and XE is the Oracle
service name.
• Username: username of’the oracle database
• Password: Password for the database user.
Database URL Formulation
• DriverManager.getConnection() method
• getConnection(String url)
• getConnection(String url, Properties prop)
• getConnection(String url, String user, String password)
Following table lists down the popular JDBC driver names and database URL.
RDBMS jDBC driver name URL format
MySQL com, m/sq1,jctbc. Driver jdbc:mysql://hostriame/ databaseName
ORACLE oracle.jdbc. driver.OracleDriver
jdbc:oracle:thin: hostname:port
Number: database Name
DB2 COM.ibm. db2.jdbc.net. DB2Driver jdbc:db2:hostname:port Number/ databaseName
ybase com.sybase.jdbc.SybDriver
jdbc:sybase:TdS.hostname: port
Number /databaseName
Create the statement object
* The JDBC Statement,
• CallableStatement, and
* PreparedStatementinterfaces define the methods and properties that enable you
to send SQL or PL/SQL commands and receive data from your database.
Interfaces
Statement
PreparedStatement
CallableStatement
Recommended Use
Use the for general-purpose access to your database. Useful when you are
using static SQL statements at runtime. The Statement interface cannot
accept parameters.
use the when you plan to use tiie SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
Use the when you want to access tiie database stored procedures. The
CallableStatement interface can also accept runtime input parameters.
Statement
• Statement
Statement stmt = null;
ry (
stmt - conn.createStatement( );
catch (SQLException e) (
finally (
stmt.close();
PreparedStatement
• PreparedStatement
PreparedStatement pstmt = null;
String SQL - "Update Employees SET age - ? WHERE id - ?";
pstmt = conn.prepareStatement(SOL);
catch (SQLException e) (
finally (
pstmt.close();
Create a table in oracle database
• create table emp(i‹l number(10), name varchar2(ß0),a$e num
Example with Oracle database
import java.sqI.*;
class OracleCon(
public static void main(String args[])(
t Y
(
//step1 load the driver class
Class.forName("oracIe.jdbc.driver.OracIeDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:x system","oracIe
//step3 create the statement object
Statement stmt=con.createstatement();
//step4 execute query
ResultSet rs-stmt.executeOuery("select "from emp");
while(rs.next())
System.out.printIn(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
catch(Exception e)( System.out.println(e);)
Load ojdbc14.jar
Two ways to load the jar file:
• paste the ojdbc14.jar file in jrc/lib/ext folder
• set classpath
1) paste the ojdbcl4.jar file in JRE/lib /ext folcler:
• Firstly, search thc ojdbc14.jar tile thcn go to JRE/1ib/ ext folder
and paste the jar file hcrc.
2) set classpath:
• There are two v ays to set the classpath: temporarjr
• permancnt
set the classpath
How to set the temporary classpath
• Firstly, search the ojdbc14.jar file then open command prompt and
write:
• C: >set classpath-c: folderojdbc 14.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 apporacleproducts 10. 2
.
0 serverjdbc libojdbc14.
jar;. ;
Example to connect to the mysql database
• Driver class: driver class fOr the mysql database is
com.mysql.jdbc.Driver.
• Connection URL: The connection URL for the mysql
database is jdbc:mysql:/ /IP:3306/db name
• Where 3306 is the port number and db name is the database
name.
• Username: The default username for the mysql database is
root.
• Password: Password of thc databasc
Example with mysql database
import java.sql.*;
class MysqlCon(
public static void main(Strings args) (
Class.forName(’com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection(”jdbc:mysq/.'//localhost.'3306/db name",”root",”root”),
Statement stmt=con.createStatement():
ResultSet rs=stmt.executeQuery("select * from emp
while(rs.next())
System.our.pr’nt/n(rs.get/nt(1)+” "mrs.getString(2)+” ”mrs.gatString(3)),
con.closet);
catch (Exception e) (
e.printStackTrace():
Load the jar file
Two ways to load the jar file:
• paste the mysq1connector.jar file in jre/lib/ext folder
• set classpath
jar file : mysql connector-java S.0.8-bin.jar
As we describe before...
Connectivity with Access without DSN
• There are to‹j raprgto connect java agglication o-ith the
acccss database.
• With‹iut D SN (Data S‹iurce Name)
• With DSN
Example with access without DSN
import java.sql.*;
class Test(
public static void main(String ar[])(
t y(
String database="student.mdb',//Here database exists in the current dire
String url="jdbc:odbc:Driver=(MicrosoftAccess Driver (*.mdb));
DBQ=" + database + ”;Dr verID-22;READONLY=true”;
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st-c.createStatement();
ResultSet rs-st.executeQuery("select “mom login' );
while(rs.next())(
System.out.printIn(rs.getString(1));
)catch(Exception ee)(System.out.printIn(ee);)
Example with access with DSN
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.printIn(rs.getString(1));
)catch(Exception ee){System.out.printIn(ee);)
ResultSet interface
• The r›bject Of ResultSet maintains a cursor pr›intin/ to a
particular row of data. Initially, cursor points to before the
first row.
• But u e can make this object to more form ard and backward
direction by passing either TYPE SCROLL INSENSITIVE
or TYPE SCROLL_SENSITIVE in crcatcStatcrncnt(int,int)
method as well as we can make this object as updatable by:
Statement stmt - con.createStatement(ResuItSet.TYPE SCROLL INSENSITIVE,
ResuItSet.CONCUR UPDATABLE);
Type of ResultSet
Type Description
ResultSet.TYPE FORWARD ONLY
The cursor can only move forward in the result
set.
ResultSet.TYPE SCROLL INSENSITIVE
The cursor can scroll forward and backward, and
the result set is not sensitive to changes made by
others to the database that occur after the result
set was created.
ResultSet.TYPE SCROLL SENSITIVE.
The cursor can scroll forward and backward, and
the result set is sensitive to changes made by
others to the database that occur after the result
set was created.
Commonly used methods of ResultSet
interface
I) 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
}›osition.
3} public boolean first(): is used tomove the cursor to the first row in result set object.
4} public boolean last(): is used to move the cursor to the last row in result set object.
5} public boolean absolute(int row):
is used to move the cursor to the specified row number in the
ResultSet object.
6} public boolean relative(int row}:
is used to move the cursor to the relative row number in the
ResultSet object, it ma7be positive or negative.
7) public int getInt(int cnlumnIndex):
is used to return the data of specified column index of the current
row as int.
8} public int getInt(String columnName):
is used to return the data of specified column name of the current
rnw as int.
9} public String getString(int columnlndex):
is used to return the data of specified column index of the current
rnw as String.
10) public String getString(String columnName):
is used to return the data of specified column name of the current
row as String.
Example of Scrollable ResultSet
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:@IocaIhost:1521:xe",
"system","oracIe");
Statement stmt-con.createStatement(ResuItSet.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.printIn(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
I)
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 ernp values(?,?,?)";
Why use PreparedStatement?
• Improves performance: The performance ot the
application will be faster if you use PreparedStatement
interface because query is compiled only once.
Methods of PreparedStatement interface
Method
public void set1nt(int paramlndex, int value) sets the integer value to the given parameter index.
public void sctString(int paramlndcx, String value) scts the String value to thc givcn parameter index.
public void setFloat(int paiamlndex, float value) sets the flnat value th the given parameter index.
public void setDouble(int paramlndex, double value) sets the double value to the given parameter index.
public int cxccutcUpdatc()
executes the query. lt is used fur create, drop, insert,
update, delete etc.
public ResultSet executeQuery()
executes the select query. It returns an instance of
ResultSet.
Example of PreparedStatement interface
that inserts the record
create table emp(id number(10),name varchar2(50));
import java.sql.*;
class InsertPrepared(
public static void main(String args[])(
Class.forName("oracle.jdbc, driver.OracleDriver");
Connection con-DriverManager.getConnection("jdbc:oracle:thin: @localhost: IS 21:xe","System","oracle");
PreparedStatement stmt con.prepareStatement("insert into Errip 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+" recorcls 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 ? 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");
CallableStatement
* Suppose, you need to execute the following Oracle stored
procedure —
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUTVARCHAR) AS
BEGIN
SELECT first INTO EMP FIRST
FROM Employees
WHERE ID = EMP_IO; CallableStatement cstmt null;
String SQL "(call getEmpName (?, ?)}";
cstmt - conn.prepareCall (SQL);
catch (SQLException e) (
cstmt. close();
CallableStatement
* Suppose, you need to execute the following Oracle stored
procedure —
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUTVARCHAR) AS
BEGIN
SELECT first INTO EMP FIRST
FROM Employees
WHERE ID = EMP_IO; CallableStatement cstmt null;
String SQL "(call getEmpName (?, ?)}";
cstmt - conn.prepareCall (SQL);
catch (SQLException e) (
cstmt. close();
How to get the instance of
CallableStatement?
• The prepareCall() method of Connection interface returns
the instance of CallableStatement. Syntax is given below:
• pulalic CallableStatement prepareCall(" ( call procedurename(?,?.. .?)) ");
• The example to get the instance of CallableStaternent is given
below:
° CallableStatement .stmt—con.prel»areCall(" (call my procedure(?,?)} ");
Example call stored procedure
using JDBC
create table user420(id number(10), name varchar2(200));
create or replace procedure "IN$E
RTR"
(id IN NuMBrR,
name lN VARCHAR2)
begin
insert into user420 values(id,name
import java.sql.*;
public class Proc (
public static void main(String[] args) throws Exception
Class.for Name("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin: @localliost: IS 21:xe","system","oracle");
CallableStatement stmt con.prepareCall(" (call insertR(?,?)} ");
stmt,setInt(1,1011);
stmt.set String(2,"Amit");
stmt.execute();
System. out,print1n("success");
Example to call the function using
JDBC
create or replace function sum4
(n 1 in number,n2 in number)
return number
temp number(8);
begin
temp :-n I+n2;
return temp;
import java.sql.*;
public class FuncSurn (
public static void main(String[] args) tlirows Exception
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con-DriverManager.getConnection(
"jdbc:oracle:thin:@localliost: 1521:xe","system","oracle");
CallableStatement stmt-con, prepareCaJl(" (?= call sum4(?,?)) ");
stmt.setlnt(2,10);
stmt,setlnt(3,43);
SŁmt.registerQutParameter(1,T/]aeS.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
• ACID stands for Atoniicit), Consistency, isolation and
durability.
ACI
• Atomicity mcans either all succcksful or none.
• Consistency A transaction reaching its normal end, thereb} committing
its results, preserves the consistenc} of the database. In other vorcls, each
successful transaction by definition commits only legal results.
• Isolation ensures that trankaction ik ikOlatcd from other transaction.
users should bc able to ii ork in isolation, working as though hc or she is
the only uscr. Each set of changes must be isolatcd from thosc of thc othcr
uscrs.
• Durability means once a transaction has lieen committed, it will remain
so, even in the event of errors, power loss etc.
Advantage of Transaction Mangaement
• It mbea the ge+formance fast because database is hit at the
Transaction
Transaction succeeded
rol1back
Transaction failed
In JDBC, Connection interface provides methods to manage transaction.
Commit & Rollback
• conn.commit( );
• conn.rollback( );
’Y(
//Assumea valid connection object conn
conn.setAutoCommit(false);
Statement stmt= conn.createStatement();
String SQL - "INSERT INTO Employees " + "VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a mal1ormed SQL statement that breaks
String SQL = "INSERTED IN Employees " + "VALUES (107, 22, 'Sita', 'Sing
stmt.executeUpdate(SQL);
// If there is no error.
conn.commit();
)catch(SOLException se)(
// If there is any error.
conn.rollback();
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.OracIeDriver");
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();
Commit & Rollback Using Savepoints
• setSavepoint(String savepointName
• releaseSavepoint(Savepoint savepointName)
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt - conn.createStatement();
//set a Savepoint
Savepoint savepoint1 = conn.setSavepoint("Savepoint1");
String SQL = "INSERT INTO Employees " + "VALUES (106, 20, 'Rita', 'Tez’)";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " + "VALUES (107, 22, ’Sita', 'Tez')";
stmt.executeUpdate(SQL);
// If there is no error, commit the changes.
conn.commit();
}catch(SOLException se)(
// If there is any error.
conn.rollback(savepoint1);
Batch Processing in DBC
• Instead Of executing a single que r A
m
pcan execute a batch
(group) of queries. It makcs the performance fast.
• Thc java.sql.Statement and java.sql. PreparedStatement
interfaces provide methods for batch processing.
Advantage of Batch Processing
• Advantage of Batch Processing
Fast Performance
• Methods of Statement interface
Method Description
void addBatch(String query) It adds quer}' into batch.
int[] executeBatch() It executes the match of queries.
Example of batch processing in jdbc
import java.sql.*;
class FetchRecords(
public static void main(String args[])throws Exception(
Class.forName("oracle.jdbc.driver.OracIeDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@IocaIhost:1521:xe","sy
stem","oracIe");
con.setAutoCommit(false);
Statement stmt—con.createStatement();
stmt.addBatch("insert into user420 values(190,'abhi',40000)");
stmt.addBatch("insert into user420 values(191,’umesh',50000)");
stmt.executeBatch();//executing the batch
con.commit();
con.close();
I)
Example of batch processing in jdbc
import java.sql.*;
class FetchRecords(
public static void main(String args[])throws Exception(
Class.forName("oracle.jdbc.driver.OracIeDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@IocaIhost:1521:xe","sy
stem","oracIe");
con.setAutoCommit(false);
Statement stmt—con.createStatement();
stmt.addBatch("insert into user420 values(190,'abhi',40000)");
stmt.addBatch("insert into user420 values(191,’umesh',50000)");
stmt.executeBatch();//executing the batch
con.commit();
con.close();
I)
Java Programs

More Related Content

Similar to java database connectivity for java programming (20)

PPT
Basic Java Database Connectivity(JDBC)
suraj pandey
 
PPTX
Jdbc introduction
Rakesh Kumar Ray
 
PPTX
chapter 5 java.pptx
BekiTube
 
PPT
Jdbc connectivity
arikazukito
 
PPT
Java database connectivity
Vaishali Modi
 
PPT
Java database connectivity
Vaishali Modi
 
PPTX
jdbc-130913021409-phpapp01000988www.pptx
ssuser8878c1
 
PDF
Unit 5.pdf
saturo3011
 
PPTX
Java Database Connectivity (JDBC)
Pooja Talreja
 
PPT
Unit 5-jdbc2
msafad
 
PPTX
java 4 Part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
PDF
Jdbc
haribee2000
 
PPTX
OOP Lecture 17-DB Connectivity-Part1.pptx
Tanzila Kehkashan
 
PPTX
jdbc concepts in java jdbc programming- programming
yatakonakiran2
 
PPTX
JDBC2 JDBCJDBCJDBCJDBCJDBCJDBCJDBCJDBCJDBC
yatakonakiran2
 
DOC
Java database programming with jdbc
sriram raj
 
Basic Java Database Connectivity(JDBC)
suraj pandey
 
Jdbc introduction
Rakesh Kumar Ray
 
chapter 5 java.pptx
BekiTube
 
Jdbc connectivity
arikazukito
 
Java database connectivity
Vaishali Modi
 
Java database connectivity
Vaishali Modi
 
jdbc-130913021409-phpapp01000988www.pptx
ssuser8878c1
 
Unit 5.pdf
saturo3011
 
Java Database Connectivity (JDBC)
Pooja Talreja
 
Unit 5-jdbc2
msafad
 
java 4 Part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
OOP Lecture 17-DB Connectivity-Part1.pptx
Tanzila Kehkashan
 
jdbc concepts in java jdbc programming- programming
yatakonakiran2
 
JDBC2 JDBCJDBCJDBCJDBCJDBCJDBCJDBCJDBCJDBC
yatakonakiran2
 
Java database programming with jdbc
sriram raj
 

Recently uploaded (20)

PPTX
Precooling and Refrigerated storage.pptx
ThongamSunita
 
PPSX
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
PDF
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
AlqualsaDIResearchGr
 
PDF
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 
PPTX
WHO And BIS std- for water quality .pptx
dhanashree78
 
PPTX
How to Un-Obsolete Your Legacy Keypad Design
Epec Engineered Technologies
 
PPTX
Work at Height training for workers .pptx
cecos12
 
PDF
Rapid Prototyping for XR: Lecture 3 - Video and Paper Prototyping
Mark Billinghurst
 
PPTX
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
PPTX
MATERIAL SCIENCE LECTURE NOTES FOR DIPLOMA STUDENTS
SAMEER VISHWAKARMA
 
PDF
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
PDF
Validating a Citizen Observatories enabling Platform by completing a Citizen ...
Diego López-de-Ipiña González-de-Artaza
 
PPTX
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
PDF
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
PDF
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 
PPTX
LECTURE 7 COMPUTATIONS OF LEVELING DATA APRIL 2025.pptx
rr22001247
 
PPTX
Stability of IBR Dominated Grids - IEEE PEDG 2025 - short.pptx
ssuser307730
 
PDF
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
PPTX
Kel.3_A_Review_on_Internet_of_Things_for_Defense_v3.pptx
Endang Saefullah
 
PPTX
Functions in Python Programming Language
BeulahS2
 
Precooling and Refrigerated storage.pptx
ThongamSunita
 
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
AlqualsaDIResearchGr
 
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 
WHO And BIS std- for water quality .pptx
dhanashree78
 
How to Un-Obsolete Your Legacy Keypad Design
Epec Engineered Technologies
 
Work at Height training for workers .pptx
cecos12
 
Rapid Prototyping for XR: Lecture 3 - Video and Paper Prototyping
Mark Billinghurst
 
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
MATERIAL SCIENCE LECTURE NOTES FOR DIPLOMA STUDENTS
SAMEER VISHWAKARMA
 
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
Validating a Citizen Observatories enabling Platform by completing a Citizen ...
Diego López-de-Ipiña González-de-Artaza
 
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 
LECTURE 7 COMPUTATIONS OF LEVELING DATA APRIL 2025.pptx
rr22001247
 
Stability of IBR Dominated Grids - IEEE PEDG 2025 - short.pptx
ssuser307730
 
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
Kel.3_A_Review_on_Internet_of_Things_for_Defense_v3.pptx
Endang Saefullah
 
Functions in Python Programming Language
BeulahS2
 
Ad

java database connectivity for java programming

  • 2. JDBC • Java JDBC is a ja a API tr› ctinnect an‹l execute query with the database. • JDBC API uses jdbc drirers to connect with the database.
  • 4. Why use JDBC • betore JDBC, ODBC API was the database API to connect and cxccutc query with the database. • But, ODBC API uses ODBC driver which is o-ritten in C languagc (i. c. platform clcpcndcnt ancl un.sccurccl). That is why Java has defined its own APl (JDBC APl) that uses JDBC drirers (written in Jara language) .
  • 5. 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 drircr Native—API driver (partially java driver) Network Protocol driver (fully java driver) Thin driver (fully java driver)
  • 6. JDBC-ODBC bridge driver When Jax-a first came out, this was a useful driver because mtist databases only supported ODBC access but now this type of driver is recommended only ftir experimental use or when no other alternative is available. 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.
  • 7. JDBC-ODBC bridge driver When Jax-a first came out, this was a useful driver because mtist databases only supported ODBC access but now this type of driver is recommended only ftir experimental use or when no other alternative is available. 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.
  • 8. Native-API driver Aclvantage: • performance upgraded than JDBC ODBC bridge drivcr. Disadvantage: be installecl ‹in the each client • The Vendor client library nccds to be installed on clicnt machine.
  • 9. Native-API driver Aclvantage: • performance upgraded than JDBC ODBC bridge drivcr. Disadvantage: be installecl ‹in the each client • The Vendor client library nccds to be installed on clicnt machine.
  • 10. Network Protocol river Aclvantage: • No clicnt side librar)' is required because of application server that can perform many tasks like auditing, load balancing, loping etc. Disadvantages: • Network sugpt)rt is required ‹in client machine. • Rcquircs databasc-specific coding to be donc in the middle tier. • Maintenance of Network Protocol driver liecomes costl)° because it requires database-specific cooling to be clone in the middle tier.
  • 11. Network Protocol river Aclvantage: • No clicnt side librar)' is required because of application server that can perform many tasks like auditing, load balancing, loping etc. Disadvantages: • Network sugpt)rt is required ‹in client machine. • Rcquircs databasc-specific coding to be donc in the middle tier. • Maintenance of Network Protocol driver liecomes costl)° because it requires database-specific cooling to be clone in the middle tier.
  • 12. Network Protocol river Aclvantage: • No clicnt side librar)' is required because of application server that can perform many tasks like auditing, load balancing, loping etc. Disadvantages: • Network sugpt)rt is required ‹in client machine. • Rcquircs databasc-specific coding to be donc in the middle tier. • Maintenance of Network Protocol driver liecomes costl)° because it requires database-specific cooling to be clone in the middle tier.
  • 13. Thin driver Aclvantage: • Better performance than all other drirers. • Nti soltirare is required at client sicle or serrer sicle. Disadvantage: • Dripcrs depends on the Database.
  • 14. Thin driver Aclvantage: • Better performance than all other drirers. • Nti soltirare is required at client sicle or serrer sicle. Disadvantage: • Dripcrs depends on the Database.
  • 15. Which Driver shou be Used? • Native-API driver dri›ers are useful in situations, 7here Network Protocol clriver or Thin clriver is not available vet tor jour database. • JDBC-ODBC bridge driver driver is not considered a ‹lepltiyment-level driver, an‹l is tygicall rused fr)r dc›c1oprncnt ancl tcstin$ purposes only.
  • 16. Which Driver shou be Used? • Native-API driver dri›ers are useful in situations, 7here Network Protocol clriver or Thin clriver is not available vet tor jour database. • JDBC-ODBC bridge driver driver is not considered a ‹lepltiyment-level driver, an‹l is tygicall rused fr)r dc›c1oprncnt ancl tcstin$ purposes only.
  • 17. Typical JDBC Programming Procedure Loach thc databasc rhi› ‹n Ol tain a ‹’erms rtion Create and cxecute statt ou rite (SQL querics) Use i ‹.hilt sets (tables) to narigate through the results t/los‹ the connection
  • 18. JDBC Programming Procedure • Load the database driver using ClOSSLOOder : • Class.forName(“oracle.jdbc.driver.OrocIeDriver“): • Establish connection with the Oracle database • connection con=DriverManager.getConnection( "jdbc:oracle:thin: @localhost:1fi21:xe","system","password"): • Create the statement object • Statement stmt=con.createstatement(): • Execute the query ResultSet rs-stmt.executeQuery("select * from emp"); while(rs.next())( System.out.println(is.getInt(1 )+ " "+rs.getString(2)); • Close the connection con. close();
  • 19. Register DBC Driver Approach I - Class.forName() • The most common approach to register a driver is to use Java's Class.forName() method • Class.for Name("oracle.jdbc.driver.OracleDriver"); • OR • Class.forName("oracle.jdbc.driver.OracleDriver"),newlnctance(); • Approach II - DriverManager.registerDriver() • Driver myDriver - new oracle.jdbc. driver.OracleDriver(); DriverManager.registerDriver( myDriver ) i
  • 20. Example to connect to the Oracle database • Driver class: driver class fOr the oracle database is oracle.jdbc.driver.OracleDriver. • Connection URL: The connection URL for the Oracle database is jdbc:oracle:thin:@IP:1521:xe • Where, IS21 is the port number and XE is the Oracle service name. • Username: username of’the oracle database • Password: Password for the database user.
  • 21. Database URL Formulation • DriverManager.getConnection() method • getConnection(String url) • getConnection(String url, Properties prop) • getConnection(String url, String user, String password) Following table lists down the popular JDBC driver names and database URL. RDBMS jDBC driver name URL format MySQL com, m/sq1,jctbc. Driver jdbc:mysql://hostriame/ databaseName ORACLE oracle.jdbc. driver.OracleDriver jdbc:oracle:thin: hostname:port Number: database Name DB2 COM.ibm. db2.jdbc.net. DB2Driver jdbc:db2:hostname:port Number/ databaseName ybase com.sybase.jdbc.SybDriver jdbc:sybase:TdS.hostname: port Number /databaseName
  • 22. Create the statement object * The JDBC Statement, • CallableStatement, and * PreparedStatementinterfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database. Interfaces Statement PreparedStatement CallableStatement Recommended Use Use the for general-purpose access to your database. Useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters. use the when you plan to use tiie SQL statements many times. The PreparedStatement interface accepts input parameters at runtime. Use the when you want to access tiie database stored procedures. The CallableStatement interface can also accept runtime input parameters.
  • 23. Statement • Statement Statement stmt = null; ry ( stmt - conn.createStatement( ); catch (SQLException e) ( finally ( stmt.close();
  • 24. PreparedStatement • PreparedStatement PreparedStatement pstmt = null; String SQL - "Update Employees SET age - ? WHERE id - ?"; pstmt = conn.prepareStatement(SOL); catch (SQLException e) ( finally ( pstmt.close();
  • 25. Create a table in oracle database • create table emp(i‹l number(10), name varchar2(ß0),a$e num
  • 26. Example with Oracle database import java.sqI.*; class OracleCon( public static void main(String args[])( t Y ( //step1 load the driver class Class.forName("oracIe.jdbc.driver.OracIeDriver"); //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:x system","oracIe //step3 create the statement object Statement stmt=con.createstatement(); //step4 execute query ResultSet rs-stmt.executeOuery("select "from emp"); while(rs.next()) System.out.printIn(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)); //step5 close the connection object con.close(); catch(Exception e)( System.out.println(e);)
  • 27. Load ojdbc14.jar Two ways to load the jar file: • paste the ojdbc14.jar file in jrc/lib/ext folder • set classpath 1) paste the ojdbcl4.jar file in JRE/lib /ext folcler: • Firstly, search thc ojdbc14.jar tile thcn go to JRE/1ib/ ext folder and paste the jar file hcrc. 2) set classpath: • There are two v ays to set the classpath: temporarjr • permancnt
  • 28. set the classpath How to set the temporary classpath • Firstly, search the ojdbc14.jar file then open command prompt and write: • C: >set classpath-c: folderojdbc 14.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 apporacleproducts 10. 2 . 0 serverjdbc libojdbc14. jar;. ;
  • 29. Example to connect to the mysql database • Driver class: driver class fOr the mysql database is com.mysql.jdbc.Driver. • Connection URL: The connection URL for the mysql database is jdbc:mysql:/ /IP:3306/db name • Where 3306 is the port number and db name is the database name. • Username: The default username for the mysql database is root. • Password: Password of thc databasc
  • 30. Example with mysql database import java.sql.*; class MysqlCon( public static void main(Strings args) ( Class.forName(’com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection(”jdbc:mysq/.'//localhost.'3306/db name",”root",”root”), Statement stmt=con.createStatement(): ResultSet rs=stmt.executeQuery("select * from emp while(rs.next()) System.our.pr’nt/n(rs.get/nt(1)+” "mrs.getString(2)+” ”mrs.gatString(3)), con.closet); catch (Exception e) ( e.printStackTrace():
  • 31. Load the jar file Two ways to load the jar file: • paste the mysq1connector.jar file in jre/lib/ext folder • set classpath jar file : mysql connector-java S.0.8-bin.jar As we describe before...
  • 32. Connectivity with Access without DSN • There are to‹j raprgto connect java agglication o-ith the acccss database. • With‹iut D SN (Data S‹iurce Name) • With DSN
  • 33. Example with access without DSN import java.sql.*; class Test( public static void main(String ar[])( t y( String database="student.mdb',//Here database exists in the current dire String url="jdbc:odbc:Driver=(MicrosoftAccess Driver (*.mdb)); DBQ=" + database + ”;Dr verID-22;READONLY=true”; Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection(url); Statement st-c.createStatement(); ResultSet rs-st.executeQuery("select “mom login' ); while(rs.next())( System.out.printIn(rs.getString(1)); )catch(Exception ee)(System.out.printIn(ee);)
  • 34. Example with access with DSN 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.printIn(rs.getString(1)); )catch(Exception ee){System.out.printIn(ee);)
  • 35. ResultSet interface • The r›bject Of ResultSet maintains a cursor pr›intin/ to a particular row of data. Initially, cursor points to before the first row. • But u e can make this object to more form ard and backward direction by passing either TYPE SCROLL INSENSITIVE or TYPE SCROLL_SENSITIVE in crcatcStatcrncnt(int,int) method as well as we can make this object as updatable by: Statement stmt - con.createStatement(ResuItSet.TYPE SCROLL INSENSITIVE, ResuItSet.CONCUR UPDATABLE);
  • 36. Type of ResultSet Type Description ResultSet.TYPE FORWARD ONLY The cursor can only move forward in the result set. ResultSet.TYPE SCROLL INSENSITIVE The cursor can scroll forward and backward, and the result set is not sensitive to changes made by others to the database that occur after the result set was created. ResultSet.TYPE SCROLL SENSITIVE. The cursor can scroll forward and backward, and the result set is sensitive to changes made by others to the database that occur after the result set was created.
  • 37. Commonly used methods of ResultSet interface I) 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 }›osition. 3} public boolean first(): is used tomove the cursor to the first row in result set object. 4} public boolean last(): is used to move the cursor to the last row in result set object. 5} public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet object. 6} public boolean relative(int row}: is used to move the cursor to the relative row number in the ResultSet object, it ma7be positive or negative. 7) public int getInt(int cnlumnIndex): is used to return the data of specified column index of the current row as int. 8} public int getInt(String columnName): is used to return the data of specified column name of the current rnw as int. 9} public String getString(int columnlndex): is used to return the data of specified column index of the current rnw as String. 10) public String getString(String columnName): is used to return the data of specified column name of the current row as String.
  • 38. Example of Scrollable ResultSet 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:@IocaIhost:1521:xe", "system","oracIe"); Statement stmt-con.createStatement(ResuItSet.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.printIn(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)); con.close(); I)
  • 39. 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 ernp values(?,?,?)";
  • 40. Why use PreparedStatement? • Improves performance: The performance ot the application will be faster if you use PreparedStatement interface because query is compiled only once.
  • 41. Methods of PreparedStatement interface Method public void set1nt(int paramlndex, int value) sets the integer value to the given parameter index. public void sctString(int paramlndcx, String value) scts the String value to thc givcn parameter index. public void setFloat(int paiamlndex, float value) sets the flnat value th the given parameter index. public void setDouble(int paramlndex, double value) sets the double value to the given parameter index. public int cxccutcUpdatc() executes the query. lt is used fur create, drop, insert, update, delete etc. public ResultSet executeQuery() executes the select query. It returns an instance of ResultSet.
  • 42. Example of PreparedStatement interface that inserts the record create table emp(id number(10),name varchar2(50)); import java.sql.*; class InsertPrepared( public static void main(String args[])( Class.forName("oracle.jdbc, driver.OracleDriver"); Connection con-DriverManager.getConnection("jdbc:oracle:thin: @localhost: IS 21:xe","System","oracle"); PreparedStatement stmt con.prepareStatement("insert into Errip 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+" recorcls inserted"); con.close(); } catch(Exception e)( System. out,println(e);)
  • 43. Example of PreparedStatement interface that updates the record PreparedStatement stmt-con.prepareStatement("update emp set 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");
  • 44. CallableStatement * Suppose, you need to execute the following Oracle stored procedure — CREATE OR REPLACE PROCEDURE getEmpName (EMP_ID IN NUMBER, EMP_FIRST OUTVARCHAR) AS BEGIN SELECT first INTO EMP FIRST FROM Employees WHERE ID = EMP_IO; CallableStatement cstmt null; String SQL "(call getEmpName (?, ?)}"; cstmt - conn.prepareCall (SQL); catch (SQLException e) ( cstmt. close();
  • 45. CallableStatement * Suppose, you need to execute the following Oracle stored procedure — CREATE OR REPLACE PROCEDURE getEmpName (EMP_ID IN NUMBER, EMP_FIRST OUTVARCHAR) AS BEGIN SELECT first INTO EMP FIRST FROM Employees WHERE ID = EMP_IO; CallableStatement cstmt null; String SQL "(call getEmpName (?, ?)}"; cstmt - conn.prepareCall (SQL); catch (SQLException e) ( cstmt. close();
  • 46. How to get the instance of CallableStatement? • The prepareCall() method of Connection interface returns the instance of CallableStatement. Syntax is given below: • pulalic CallableStatement prepareCall(" ( call procedurename(?,?.. .?)) "); • The example to get the instance of CallableStaternent is given below: ° CallableStatement .stmt—con.prel»areCall(" (call my procedure(?,?)} ");
  • 47. Example call stored procedure using JDBC create table user420(id number(10), name varchar2(200)); create or replace procedure "IN$E RTR" (id IN NuMBrR, name lN VARCHAR2) begin insert into user420 values(id,name import java.sql.*; public class Proc ( public static void main(String[] args) throws Exception Class.for Name("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin: @localliost: IS 21:xe","system","oracle"); CallableStatement stmt con.prepareCall(" (call insertR(?,?)} "); stmt,setInt(1,1011); stmt.set String(2,"Amit"); stmt.execute(); System. out,print1n("success");
  • 48. Example to call the function using JDBC create or replace function sum4 (n 1 in number,n2 in number) return number temp number(8); begin temp :-n I+n2; return temp; import java.sql.*; public class FuncSurn ( public static void main(String[] args) tlirows Exception Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con-DriverManager.getConnection( "jdbc:oracle:thin:@localliost: 1521:xe","system","oracle"); CallableStatement stmt-con, prepareCaJl(" (?= call sum4(?,?)) "); stmt.setlnt(2,10); stmt,setlnt(3,43); SŁmt.registerQutParameter(1,T/]aeS.INTEGER); stmt.execute(); System. out.println(stmt.getInt(1));
  • 49. Transaction Management in JDBC • Transaction represents a single unit of work. • The ACID properties describes the transaction management • ACID stands for Atoniicit), Consistency, isolation and durability.
  • 50. ACI • Atomicity mcans either all succcksful or none. • Consistency A transaction reaching its normal end, thereb} committing its results, preserves the consistenc} of the database. In other vorcls, each successful transaction by definition commits only legal results. • Isolation ensures that trankaction ik ikOlatcd from other transaction. users should bc able to ii ork in isolation, working as though hc or she is the only uscr. Each set of changes must be isolatcd from thosc of thc othcr uscrs. • Durability means once a transaction has lieen committed, it will remain so, even in the event of errors, power loss etc.
  • 51. Advantage of Transaction Mangaement • It mbea the ge+formance fast because database is hit at the Transaction Transaction succeeded rol1back Transaction failed In JDBC, Connection interface provides methods to manage transaction.
  • 52. Commit & Rollback • conn.commit( ); • conn.rollback( ); ’Y( //Assumea valid connection object conn conn.setAutoCommit(false); Statement stmt= conn.createStatement(); String SQL - "INSERT INTO Employees " + "VALUES (106, 20, 'Rita', 'Tez')"; stmt.executeUpdate(SQL); //Submit a mal1ormed SQL statement that breaks String SQL = "INSERTED IN Employees " + "VALUES (107, 22, 'Sita', 'Sing stmt.executeUpdate(SQL); // If there is no error. conn.commit(); )catch(SOLException se)( // If there is any error. conn.rollback();
  • 53. 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.OracIeDriver"); 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();
  • 54. Commit & Rollback Using Savepoints • setSavepoint(String savepointName • releaseSavepoint(Savepoint savepointName) //Assume a valid connection object conn conn.setAutoCommit(false); Statement stmt - conn.createStatement(); //set a Savepoint Savepoint savepoint1 = conn.setSavepoint("Savepoint1"); String SQL = "INSERT INTO Employees " + "VALUES (106, 20, 'Rita', 'Tez’)"; stmt.executeUpdate(SQL); //Submit a malformed SQL statement that breaks String SQL = "INSERTED IN Employees " + "VALUES (107, 22, ’Sita', 'Tez')"; stmt.executeUpdate(SQL); // If there is no error, commit the changes. conn.commit(); }catch(SOLException se)( // If there is any error. conn.rollback(savepoint1);
  • 55. Batch Processing in DBC • Instead Of executing a single que r A m pcan execute a batch (group) of queries. It makcs the performance fast. • Thc java.sql.Statement and java.sql. PreparedStatement interfaces provide methods for batch processing.
  • 56. Advantage of Batch Processing • Advantage of Batch Processing Fast Performance • Methods of Statement interface Method Description void addBatch(String query) It adds quer}' into batch. int[] executeBatch() It executes the match of queries.
  • 57. Example of batch processing in jdbc import java.sql.*; class FetchRecords( public static void main(String args[])throws Exception( Class.forName("oracle.jdbc.driver.OracIeDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@IocaIhost:1521:xe","sy stem","oracIe"); con.setAutoCommit(false); Statement stmt—con.createStatement(); stmt.addBatch("insert into user420 values(190,'abhi',40000)"); stmt.addBatch("insert into user420 values(191,’umesh',50000)"); stmt.executeBatch();//executing the batch con.commit(); con.close(); I)
  • 58. Example of batch processing in jdbc import java.sql.*; class FetchRecords( public static void main(String args[])throws Exception( Class.forName("oracle.jdbc.driver.OracIeDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@IocaIhost:1521:xe","sy stem","oracIe"); con.setAutoCommit(false); Statement stmt—con.createStatement(); stmt.addBatch("insert into user420 values(190,'abhi',40000)"); stmt.addBatch("insert into user420 values(191,’umesh',50000)"); stmt.executeBatch();//executing the batch con.commit(); con.close(); I)