JDBC
JDBC
CONNECTIVITY
1
Java and the database
5
Why use JDBC
6
What is API
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
9
JDBC-ODBC bridge driver
10
Java application
JDBC API
ODBC
driver
Database Database
Advantages:
easy to use.
Disadvantages:
Performance degraded because JDBC method call is
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++
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
Native driver
ODBC Driver
(DBMS specific)
DBMS
JDBC- to ODBC driver (Type 1)
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.
.
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
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
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
}
}
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:
36
Insert data to database-
Insert Query
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
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);
//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.*;
// Database credentials
static final String USER = "username";
static final String PASS = "password";
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.*;
// Database credentials
static final String USER = "username";
static final String PASS = "password";
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
Process
results
Close
Connect
Close
Connect
Query
Step through the results
Close
Connect
Query
Close the result set
Process
results Close the statement
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.
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");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
}
55
Example of PreparedStatement
interface that updates the record
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.
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:
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;
/
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");
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.
64
Example cont..
import java.sql.*;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
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.
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);
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();
}
}
con.commit();
System.out.println("record successfully saved");
}}
70