Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
JDBC – Java Database Connectivity
1
JDBC
• JDBC stands for "Java DataBase Connectivity".
• JDBC™ is an API developed by Sun Microsystems that
provides a standard way to access data using the Java™
programming language.
• Using JDBC, an application can access a variety of databases
and run on any platform with a Java Virtual Machine.
• It isn't necessary to write separate applications to access
different database systems (Oracle and Sybase, for example).
• Using JDBC allows you to write one application that can send
SQL statements to different database systems.
JDBC
3
JDBC
• The JDBC API defines a set of Java interfaces
that encapsulate major database functionality,
such as
- running queries,
- processing results, and
- determining configuration information.
• Because JDBC applications are written in Java,
applications work on any platform.
How JDBC Works
• Establish a connection with a
data source
• Send queries and update
statements to the data source
• Process the results
How JDBC Works
• The Java application calls JDBC classes and interfaces to
submit SQL statements and retrieve results.
• The JDBC API is implemented through the JDBC driver.
• The JDBC Driver is a set of classes that implement the
JDBC interfaces to process JDBC calls and return result
sets to a Java application.
• The database (or data store) stores the data retrieved by
the application using the JDBC Driver.
JDBC Architecture
Oracle
Driver
Oracle
Java
Application
JDBC
DB2
Driver
Network
DB2
MySQL
Driver
MySQL
7
JDBC Architecture (cont.)
Application
JDBC
Driver
• Java code calls JDBC library
• JDBC loads a driver
• Driver talks to a particular database
• An application can work with several databases by using all
corresponding drivers
• Ideal: can change database engines without changing any
application code .
JDBC API
• DataSource Object
• Connection Object
• Statement/PreparedStatement/CallableStatement
Object
• Result set Object
JDBC API
• A DataSource object is used to establish connections.
- Driver Manager can also be used to establish a connection,
connecting through a DataSource object is the preferred
method.
• A Connection object controls the connection to the
database.
- An application can alter the behavior of a connection by
invoking the methods associated with this object.
- An application uses the connection object to create
statements.
JDBC API
• Statement, PreparedStatement, and CallableStatement objects
are used for executing SQL statements.
- A PreparedStatement object is used when an application plans to reuse a
statement multiple times.
- The application prepares the SQL it plans to use. Once prepared, the
application can specify values for parameters in the prepared SQL
statement. The statement can be executed multiple times with different
parameter values specified for each execution.
- A CallableStatement is used to call stored procedures that return values.
- The CallableStatement has methods for retrieving the return values of the
stored procedure.
JDBC API
• A ResultSet object contains the results of a
query.
- A ResultSet is returned to an application when
a SQL query is executed by a statement object.
- The ResultSet object provides methods for
iterating through the results of the query.
Why JDBC?
• ODBC (Open Database Connectivity) is an established
standard API for database access.
• ODBC isn't appropriate for direct use from the Java
programming language because it uses a C interface.
• The JDBC API was modeled after ODBC, but, because
JDBC is a Java API, it offers a natural Java interface for
working with SQL.
• JDBC is needed to provide a "pure Java" solution for
application development.
JDBC API
• The JDBC API is available in the java.sql and
javax.sql packages.
• DriverManager - Loads JDBC drivers in memory.
Can also be used to open connections to a data
source.
• Connection - Represents a connection with a data
source. It is also used for creating Statement,
PreparedStatement and CallableStatement objects.
JDBC API
• Statement - Represents a static SQL statement. Can be used
to retrieve ResultSet object/s.
• PreparedStatement - Higher performance alternative to
Statement object, represents a precompiled SQL statement.
• CallableStatement - Represents a stored procedure. Can be
used to execute stored procedures in a RDBMS which
supports them.
• ResultSet - Represents a database result set generated by
using a SELECT SQL statement.
• SQLException - An exception class which encapsulates
database base access errors.
JDBC Driver Types
• JDBC drivers are divided into four types or
levels.
• Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver
(Middleware)
Type 4: All Java/Native-protocol driver (Pure)
Type 1 JDBC Driver
• JDBC-ODBC Bridge driver
• The Type 1 driver translates all JDBC calls into
ODBC calls and sends them to the ODBC driver.
• ODBC is a generic API.
• The JDBC-ODBC Bridge driver is recommended
only for experimental use or when no other
alternative is available
Type 1 JDBC Driver
• Functions:
•
Translates query obtained by JDBC
into corresponding ODBC query,
which is then handled by the ODBC
driver.
•
Sun provides a JDBC-ODBC Bridge
driver.
sun.jdbc.odbc.JdbcOdbcDriver. This
driver is native code and not Java.
• There is some overhead associated
with the translation work to go from
JDBC to ODBC.
Type 1 JDBC Driver
Advantage
• The JDBC-ODBC Bridge allows access to almost any database, since the
database's ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are
not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to
the ODBC driver, then to the database, and this applies even in the
reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
Type 2 JDBC Driver
• Native-API/partly Java driver
• The distinctive characteristic of type 2 jdbc
drivers are that Type 2 drivers convert JDBC
calls into database-specific calls i.e. this driver is
specific to a particular database.
• Some distinctive characteristic of type 2 jdbc
drivers are shown below.
• Example: Oracle will have oracle native api.
Type 2 JDBC Driver
Functions:
• This type of driver
converts JDBC calls into
calls to the client API for
that database
Type 2 JDBC Driver
Advantage
• The distinctive characteristic of type 2 jdbc drivers are that they are
typically offer better performance than the JDBC-ODBC Bridge as the
layers of communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.
Disadvantage
• 1. Native API must be installed in the Client System and hence type 2
drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a
portability issue.
3. If we change the Database we have to change the native api as it is
specific to a database
4. Usually not thread safe.
Type 3 JDBC Driver
• All Java/Net-protocol driver
• Type 3 database requests are passed through the
network to the middle-tier server.
• The middle-tier then translates the request to the
database.
Type -3 JDBC Driver
Functions:
•
Follows a three tier communication
approach.
•
Can interface to multiple databases - Not
vendor specific.
•
The JDBC Client driver written in java,
communicates with a middleware-net-server
using a database independent protocol, and
then this net server translates this request into
database commands for that database.
•
Thus the client driver to middleware
communication is database independent
Type 3 JDBC Driver
Advantage
•
1. This driver is server-based, so there is no need for any vendor database library to be
present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to
load.
5. The type 3 driver typically provides support for features such as caching (connections,
query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantage
•
It requires another server application to install and maintain.
•
Traversing the recordset may take longer, since the data comes through the backend server.
Type 4 JDBC Driver
• Native-protocol/all-Java driver
• The Type 4 uses java networking libraries to
communicate directly with the database server.
Type 4 JDBC Driver
Functions
•
Type 4 drivers are entirely written in Java that
communicate directly with a vendor's database
through socket connections.
•
No translation or middleware layers, are required,
improving performance.
•
The driver converts JDBC calls into the vendorspecific database protocol so that client applications
can communicate directly with the database server.
•
Completely implemented in Java to achieve
platform independence.
•
e.g include the widely used Oracle thin driver oracle.jdbc.driver.OracleDriver which connect to
jdbc:oracle:thin URL format.
Type 4 JDBC Driver
Advantage
• 1. The major benefit of using a type 4 jdbc drivers are that they are completely
written in Java to achieve platform independence and eliminate deployment
administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have
to translate database requests to ODBC or a native connectivity interface or to
pass the request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further,
these drivers can be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database
CRUD OPERATIONS
• CRUD stands for create, read, update, delete.
• Create statement in SQL looks like
– Create table mytab ( mynum number , name varchar2(25));
• READ statement looks like
– Select * from mytab where mynum=25;
• UPDATE statement looks as
– Update mytab set mynum=88 where mynum=25;
• DELETE statement like
– Delete from mytab where mynum=88;
DDL – DML – DCL - TCL
• DDL – Data Definition Language
– These queries are used to create database objects such as tables, indexes,
procedures, constraints
– Create , drop, alter,truncate,comment,rename
• DML – Data Manipulation Language
– These queries are used to manipulate the data in the database tables.
– Insert, update, delete, select (more available)
• DCL – Data Control Language
– These are data control queries like grant and revoke permissions
• TCL– Transaction Control Language
– These are transaction control queries like commit, revoke, savepoint, set
transaction
EXERCISE
• Create tables using primary key
• Using Foreign key relationship.
• Select Query with where clause
• Select Query with group by ,having and order by
clauses
• Insert ,Update and Delete operations.
31
CRUD and Java
• Java can invoke CRUD operations using JDBC
• JDBC is Java Database Connectivity and there
are 4 types of drivers which form a bridge
between java and a database
• The Operations communicated by java will be
translated in a form understood by the database
by the drivers.
JDBC Drivers
• Type 1 Driver - JDBC-ODBC bridge
– This is an ODBC driver, which is open source
• Type 2 Driver – Native API driver
– This is more like the OCI (Oracle Call Interface) call interface is
converted to native calls of the database.
• Type 3 Driver – Network protocol driver
– This is achieved by using a Java Driver in a middleware
• Type 4 Driver – Native Protocol Driver
– This is a driver written purely in Java Language
• We Usually prefer to depend on the Type 4 driver
Seven Steps
• Load the driver
• Define the connection URL
• Establish the connection
• Create a Statement object
• Execute a query using the Statement
• Process the result
• Close the connection
34
Loading the Driver
• We can register the driver indirectly using the statement
Class.forName("com.mysql.jdbc.Driver");
• Class.forName loads the specified class
• When mysqlDriver is loaded, it automatically
- creates an instance of itself
- registers this instance with the DriverManager
• Hence, the driver class can be given as an argument of
the application
35
DRIVERS
• ORACLE DRIVER –ojdbc6.jar or higher
versions (classes12.jar)
• http://www.java2s.com/Code/Jar/o/ojdbc6.htm
• MYSQL DRIVER –com.mysql.jdbc_5.1.5.jar
• http://www.java2s.com/Code/Jar/c/Downloadco
mmysqljdbc515jar.htm
36
An Example
//A driver for MySQL database
Class.forName("com.mysql.jdbc.Driver");
// A Driver for ORACLE database
Class.forName(" oracle.jdbc.driver.OracleDriver ");
// A Driver for NETBEANS DERBY database
Class.forName("org.apache.derby.jdbc.ClientDriver");
37
Connecting to the Database
• Every database is identified by a URL
• Given a URL, DriverManager looks for the driver
that can talk to the corresponding database
• DriverManager tries all registered drivers, until a
suitable one is found
38
Connecting to the Database
SYNTAX:
Connection con = DriverManager.
getConnection(“URL”,”username”,”password”);
Example – Establishing connection with ORACLE
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@local
host:1521:XE", “scott",“tiger");
39
Database URL
40
Example – Establishing
connection with MYSQL
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysqldb","root","root");
41
Establishing connection with
NETBEANS DERBY Data base
Class.forName("org.apache.derby.jdbc.ClientDrive
r");
Connection con=DriverManager.getConnection(
jdbc:derby://localhost:1527/DBNAME",“USERNA
ME",“PASSWORD");
Note : DBNAME,USERNAME,PASSWORD
values needs to be identified from your system.
42
Interaction with the Database
• We use Statement objects in order to
- Query the database
- Update the database
• Three different interfaces are used:
Statement, PreparedStatement, CallableStatement
• All are interfaces, hence cannot be instantiated
• They are created by the Connection
Using Statement Object
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@l
ocalhost:1521:XE", “scott",“tiger");
stmt = con.createStatement();
String sql = "INSERT INTO DEPT VALUES (50,
‘MARKETING', ‘MUMBAI’)";
stmt.executeUpdate(sql);
44
Using PreparedStatement
•Assume EMP table with columns empid,ename
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localho
st:1521:XE", “scott",“tiger");
PreparedStatement stmt=con.prepareStatement("insert
into Emp values(?,?)");
stmt.setInt(1,101);
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
45
Statement and Prepared Statement
• A Statement Interface is used to create a statement i.e. a
query to be executed against a database. In this process,
two calls are made to the database system , one to get the
table metadata and other to get the data itself. The
statement object is also compiled every time it executes.
• A Prepared statement comes in handy as it is compiled
and cached and only makes on database call when
invoked. The compilation would be skipped even if the
values in the where clause change
About Prepared Statements
• Prepared Statements are used for queries that are
executed many times
• They are parsed (compiled) by the DBMS only once
• Column values can be set after compilation
• Instead of values, use ‘?’
• Hence, Prepared Statements can be though of as
statements that contain placeholders to be substituted
later with actual values
47
executeUpdate() method
int executeUpdate (String sql)
Creates a Statement object for sending
SQL statements to the database.
Returns either the row count for INSERT,
UPDATE or DELETE statements, or 0 for SQL
statements that return nothing
Inserting a Row – Example using
Statement
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:XE", “scott",“tiger");
Statement stmt = con.createStatement();
int i= stmt.executeUpdate(“INSERT INTO pet
VALUES(12, ’minou’, ’Gwen’, ’cat’)”);
Insert record –using Prepared
Statement
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:XE", “scott",“tiger");
String query = "insert into dept(deptnum, deptname, deptloc)
values(?, ?, ?)";
pstmt = con.prepareStatement(query);
pstmt.setInt(1, 10);
pstmt.setString(2, “SALES");
pstmt.setString(3, “LONDON");
pstmt.executeUpdate();
50
UPDATE Statement
• Assume DBUSER Table with columns (USERNAME &
USER_ID)
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:XE", “scott",“tiger");
String qry = "UPDATE DBUSER SET USERNAME = ? WHERE
USER_ID = ?";
PreparedStatement ps = con.prepareStatement(qry);
ps.setString(1, “newadmin");
ps.setInt(2, 1001);
ps.executeUpdate();
51
DELETE Statement
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@local
host:1521:XE", “scott",“tiger");
String qry = "DELETE DBUSER WHERE USER_ID = ?";
PreparedStatement ps = con.prepareStatement(qry);
ps.setInt(1, 1001);
ps.executeUpdate();
52
Example
• Assume MYUSERS table with columns (USERID
(NUMBER),USERNAME (VARCAHR2(20))
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
“scott",“tiger");
PreparedStatement ps=con.prepareStatement("insert into MYUSERS
values(?,?)");
ps.setInt(1, 1001);
ps.setString(2, “ADMIN");
int a=ps.executeUpdate();
53
DEMO
54