8/9/2019 jdbc connection in java
1/50
Database access using Servlets
8/9/2019 jdbc connection in java
2/50
Introduction JDBC is a Java API (set of classes and interfaces) for executing
database (SQL) statements in a Java program.
History
Part of JDK Since JDK 1.1
Package: java.sql
Use
Create tables, insert values into them, query tables, retrieve
results from queries, and update tables.
8/9/2019 jdbc connection in java
3/50
JDBC Architecture
Application JDBC Driver Data Source
Java code calls JDBC library
JDBC loads a driver
Driver talks to a particular database Can have more than one driver -> more than one
database
8/9/2019 jdbc connection in java
4/50
JDBC drivers
Drivers are libraries used by applications to connect todatabases.
The JVM uses the JDBC driver to translate generalized JDBC
calls into vendor specific database calls.
JDBC drivers implement some of the JDBC API
8/9/2019 jdbc connection in java
5/50
Types ofJDBC Driver Type 1: JDBC-ODBC Bridge
Type 2: Part Java, Part Native Driver
Type 3: Intermediate database Access Server
Type 4: Pure Java Drivers
8/9/2019 jdbc connection in java
6/50
Type I
Bridge
Type II
Native
Type III
Middleware
Type IV
Pure
ODBC
API
ODBC
Layer
Middleware
Server
Native Code
Library
JDBC
Data
Source
Data
Source
Data
Source
Data
Source
8/9/2019 jdbc connection in java
7/50
Type 1: JDBC-ODBC Bridge The JDBC to ODBC bridge driver connects Java Program to Microsoft
ODBC (Open Database Connectivity) data sources
The Java 2 Software Development kit from Sun Microsystems
includes the JDBC-ODBC bridge
This driver requires the ODBC driver on the client computer and
normally requires configuration of ODBC data sources
Uses bridge to connect Java client to an ODBC database system.
Translates all JDBC calls into ODBC and sends them to ODBC driver
This really refers to a C program, compiled to native code, thatinterfaces the Java Virtual Machine to ODBC.
8/9/2019 jdbc connection in java
8/50
Java Application
JDBC-ODBC
BridgeJDBC
API
ODBC
Layer
ODBC
API
Data
SourceClient
Server
Translates query obtained by JDBC into corresponding ODBC query, which
is then handled by the ODBC driver.
There is some overhead associated with the translation work to go from
JDBC to ODBC
8/9/2019 jdbc connection in java
9/50
Features Standard JDK includes classes for JDBC-ODBC bridge for e.g.
sun.jdbc.odbc.JdbcOdbcDriver.
Native library is not database specific. The bridge does not need to
know about every kind of database; it only needs to know how to usethe ODBC API
Advantages:
If ODBC driver is already available, then only bridge is required.
Almost any database for which ODBC driver is installed, can be accessed.
8/9/2019 jdbc connection in java
10/50
Contd..Disadvantages
Slow
JDBC call goes thru the bridge to the ODBC driver then todatabase-specific driver.
Native code required
Data source to be defined on each client machine
8/9/2019 jdbc connection in java
11/50
Type 2: Part Java, Part Native
Driver Uses mix of Java implementation and vendor-specific native API
for data access.
Requires vendor (database-specific) binary code to be present
on client machine.
Uses a native code library to access database, wrapping a thin
layer of Java around the native library.
Converts JDBC calls into database-specific calls for databasessuch as SQL server, Oracle, Sybase etc
e.g. Oracle Driver, WebLogic drivers
8/9/2019 jdbc connection in java
12/50
J
ava Application
JDBC DriverVendor
APIJDBCAPI
Client
Data
Source
Server
Part Java, Part Native Driver
8/9/2019 jdbc connection in java
13/50
Contd..Advantage
Type 2 drivers typically offer significantly better performancethan the JDBC-ODBC Bridge. Fast, as less layers to go
Disadvantage The vendor database library needs to be loaded on each client
machine. Consequently, type 2 drivers cannot be used for theInternet.
Type 2 drivers show lower performance than type 3 and type 4drivers.
ApplicationStandalone GUI- intensive program that always runs on NT mayuse Type 2 native code driver.
8/9/2019 jdbc connection in java
14/50
Type 3: Intermediate database
Access Server Also known as JDBC-Net pure Java driver
Based on middleware database server that acts as a
gateway for multiple database servers. Uses database-independent protocol to communicate
with database gateway (vendor-neutral driver server).The middleware component might use any other typeof driver to provide actual database access.
Type 3 JDBC drivers are pure Java drivers fordatabase middleware.
e.g. Symantec
8/9/2019 jdbc connection in java
15/50
ClientJava
Application
JDBC Driver JDBC Driver
Server
Native
Driver
Data
Source
Server
JDBCAPI
JDBC calls are translated into a middleware vendor's protocol, andthe middleware converts those calls into a database's API.
Type 3 JDBC drivers offer the advantage of being server-based,meaning that they do not require native client code, which makesType 3 drivers faster than Type 1 and Type 2 drivers.
Developers can also use a single JDBC driver to connect to multipledatabases.
8/9/2019 jdbc connection in java
16/50
Contd..
Advantages:
Pure Java. No native code to be installed on client machine.
Flexible when client wants to communicate with multiple databasesfrom different vendors.
Useful for intranet applications.
Features of connection pooling, data caching etc.
Disadvantages
Type 3 drivers require database-specific coding to be done in themiddle tier.
Slow- presence of gateway. Gateway reads data from database thensends to client.
8/9/2019 jdbc connection in java
17/50
Type 4: Pure Java Drivers Also known as Native-protocol pure Java driver
Type 4 JDBC drivers are direct-to-database pure Java drivers ("thin"drivers).
Convert JDBC API calls to direct network calls using vendor-specificnetworking protocols by making direct connections with database
They understand database-specific networking protocols and canaccess database directly without any additional software.
Are completely implemented in Java to achieve platform independence
Each DBMS requires its own Type 4 driver; therefore, there are more
drivers to manage in a heterogeneous computing environment, but thisis outweighed by the fact that Type 4 drivers provide faster
performance and direct access to DBMS features.
e.g. Oracle, mySQL
8/9/2019 jdbc connection in java
18/50
ClientJava
Application
JDBC Driver
Data
Source
Server
JDBCAPI
JDBC drivers don't have to translate database requests to ODBC or anative connectivity interface or to pass the request on to another server
8/9/2019 jdbc connection in java
19/50
Contd.. Advantages:
Simplest to deploy.
Platform-independent.
Fastest, no code needs to be deployed on client machine.
Disadvantages:
Database-specific- need different driver for each database.
8/9/2019 jdbc connection in java
20/50
Driver Statement Connection ResultSet ResultSetMeta
Data
DatabaseMeta
Data
PreparedStatement
CallableStatementjava.lang.Object
java.util.date Driver Manager DriverPropertyInfo Types
Date Time TimeStamp
8/9/2019 jdbc connection in java
21/50
InterfacesDriver
public interface Driver
The interface that every driver class must implement.
The Java SQL framework allows for multiple database drivers.
Each driver should supply a class that implements the Driver interface.
The DriverManager will try to load as many drivers as it can find andthen for any given connection request, it will ask each driver in turn totry to connect to the target URL.
When a Driver class is loaded, it should create an instance of itself andregister it with the DriverManager. This means that a user can load andregister a driver by calling
Class.forName("foo.bah.Driver")
8/9/2019 jdbc connection in java
22/50
Contd.. Statement
The objective of the Statement interface is to pass to the database the
SQL string for execution and to retrieve any results from the database
in the form of a ResultSet
8/9/2019 jdbc connection in java
23/50
Contd..
Connection
When a connection is opened, this represents a single instance of a
particular database session. As long as the connection remains open,
SQL queries may be executed and results obtained.
public Statement createStatement() throws SQLException
Creates a Statement object for sending SQL statements to the
database. SQL statements without parameters are normally
executed using Statement objects. If the same SQL statement is
executed many times, it may be more efficient to use a
PreparedStatement object.
8/9/2019 jdbc connection in java
24/50
Contd..ResultSet
A ResultSet is the retrieved data from a currently executed SQL
statement.
The data from the query is delivered in the form of a table. The rows of
the table are returned to the program in sequence.
8/9/2019 jdbc connection in java
25/50
Contd..ResultSetMetaData
Provides information on the type and properties of ResultSet.
An object that can be used to get information about the types and
properties of the columns in a ResultSet object.
Methods:
getColumnCount
public int getColumnCount() throws SQLException
Returns the number of columns in this ResultSet object
8/9/2019 jdbc connection in java
26/50
Contd..isSearchable
public boolean isSearchable(int column) throws SQLException
Indicates whether the designated column can be used in a where
clause.
getColumnName
public String getColumnName(int column) throws
SQLException
Get the designated column's name.
8/9/2019 jdbc connection in java
27/50
Contd..DatabaseMetaData
Provides information on the database as a whole
What tables are available?
Is the database in read-only mode?
8/9/2019 jdbc connection in java
28/50
ClassesDriverManager
This is a very important class.
Its main purpose is to provide a means of managing thedifferent types ofJDBC database driver
On running an application, it is the DriverManager's
responsibility to load all the drivers found in the system
8/9/2019 jdbc connection in java
29/50
Typical
JDBC Programming Procedure
1. Load the database driver
2. Obtain a connection
3. Create and execute statements
4. Use result sets to navigate through the results
5. Close the connection
8/9/2019 jdbc connection in java
30/50
SQL
Code
import
java.sql.*;
class useDB
{
}
JDBC
Connectivity
UtilitiesDriver DB
8/9/2019 jdbc connection in java
31/50
Database
DriverManager
Connection Statement ResultSet
Driver
SQL Data
8/9/2019 jdbc connection in java
32/50
Used to provide common access layer on the top of differentdatabase drivers used in an application.
The DriverManager class keeps track of the registered JDBC
drivers and creates database connections. DriverManager requires that each driver required by the
application must be registered before use, so that theDriverManager is aware of it
DriverManager
8/9/2019 jdbc connection in java
33/50
DriverManager
Sybase Driver
Oracle Driver
JDBC ODBC DriverConnection
getConnection(jdbc:odbc:myLib)
8/9/2019 jdbc connection in java
34/50
DriverManager Application does not interacts directly with Driver object since
DriverManager is available.
getConnection() iterates thru the drivers that are registered with
the DriverManager and asks each one in turn if it can handle theURL that is passed.
First driver that can satisfy the connection defined by the URL creates
a connection object that is passed back to the application by the way of
DriverManager
8/9/2019 jdbc connection in java
35/50
How to load DriverManager Load the database driver using ClassLoader:
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("com.oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {/* Handle Exception */ }
When a Driver class is loaded, it should create an instance of itself and register
it with the DriverManager.
Class class: java.lang.Class- This method dynamically loads a class if it has
not already been loaded. The method returns a Class object that describes the
named classforName
public static Class forName(String className) throws ClassNotFoundException
8/9/2019 jdbc connection in java
36/50
Connecting to a Database The Connection represents a single logical database transaction.
The Connection Interface has methods for sending a series ofSQL statements to the database and managing the committing
or aborting of those statements.Type 1 JDBC Driver
try
{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection
("jdbc:odbc:dsn");
}catch(SQLException e){
e.printStackTrace();
}
8/9/2019 jdbc connection in java
37/50
Contd..Type 4 JDBC Driver
Oracle Server
try
{
Class.forName ("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:ite",
"scott", tiger");
}catch(SQLException e){
e.printStackTrace();
}
8/9/2019 jdbc connection in java
38/50
Statement Statement interface provides workspace to create SQL query,
execute it and retrieve any results that are executed.
Created by createStatement() of Connection
createStatement() throws SQLException
Statement stat = con.createStatement();
8/9/2019 jdbc connection in java
39/50
Executing SELECT
Statements A query is expected to return a set of tuples as the result, and
not change the state of the database. The executeQuery
method of the statement is used to execute a database query.
This returns a result set. The Stat.executeQuery() method is used when you want to
retrieve records from a database i.e. you are executing SELECT
SQL statements.
E.g.
ResultSet rs = stat.executeQuery("SELECT
*F
ROM
ells");ResultSet result = stat.executeQuery("SELECT name, cups FROM
JoltData ORDER BY cups DESC;");
8/9/2019 jdbc connection in java
40/50
Executing INSERT/UPDATE/DELETE Query
To INSERT, UPDATE or DELETE records from a table, make use of
Stat.executeUpdate() method
When executeUpdate is used to call DDL statements, the return
value is always zero, while data modification statementexecutions will return a value greater than or equal to zero,which is the number of tuples affected in the relation
8/9/2019 jdbc connection in java
41/50
Contd.. Create a simple table, which stores an employee ID and name
stat.executeUpdate (CREATE TABLE EMPLOYEE (Emp_Id
number(5), Emp_Name varchar(20)));
Insert data into employee, so the table contains datastat.executeUpdate (INSERT INTO EMPLOYEE VALUES (1,
'John')");
Commit changes
conn.commit();
Delete a record
int recordsUpdated;
recordsUpdated = st.executeUpdate("DELETE FROM
EMPLOYEE WHERE Emp_Id = 1");
8/9/2019 jdbc connection in java
42/50
ResultSet The ResultSet interface allows to access data returned from an
SQL query.
ResultSet results = stmt.executeQuery( SELECT Emp_Id,
Emp_Name FROM EMPLOYEE);
while (results.next())
{
int Id = results.getInt(Emp_Id");
String Name = results.getString(Emp_Name");
}
8/9/2019 jdbc connection in java
43/50
Contd.. The get method has two forms by which data can be accessed.
In the first form, column name of the table is specified while inthe second form the position of that column in the table isspecified.
Retrieving a result by index is faster than retrieving a result bycolumn name. But the disadvantage is that the code is harder tomaintain.
Updating data from ResultSet
Update values in result set and store updates back into
database. E.g.
results.updateString(column_name, new_value);
results.updateRow();
results.updateString(Emp_Name",Name.toUpperCase());
8/9/2019 jdbc connection in java
44/50
8/9/2019 jdbc connection in java
45/50
8/9/2019 jdbc connection in java
46/50
8/9/2019 jdbc connection in java
47/50
import java.io.*;
import java.lang.Object;
import java.sql.*;
public class JdbcTest {
public static void main(String args[]){
Connection dbConn=null;
Statement stat=null;try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dbConn=DriverManager.getConnection("jdbc:odbc:test2","scott","tiger");
stat = dbConn.createStatement();
}catch(SQLException e){
System.out.println(e); }
catch(ClassNotFoundException e){System.out.println(e); }
8/9/2019 jdbc connection in java
48/50
try{
ResultSet customers= stat.executeQuery("SELECT CustomerID, CompanyName, City,
Country FROM customers");
System.out.println("CUSTOMER LIST");
while(customers.next())
{
System.out.println( customers.getString("CustomerID"));
System.out.println(customers.getString("CompanyName"));
System.out.println(customers.getString("City"));
System.out.println(customers.getString("Country"));
}
}catch(Exception e){
e.printStackTrace();
}
}
}
8/9/2019 jdbc connection in java
49/50
Handling database connections in Servlets
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class JdbcServlet extends HttpServlet
Connection con = null; // dbase connection, 1 per pooled servlet instancepublic void init(ServletConfig config) throws ServletException{
super.init(config);
// Establish the connection for this instance
con = establishConnection();
con.setAutoCommit(false);
}
8/9/2019 jdbc connection in java
50/50
public void doGet(HttpServletRequest req, HttpServletResponse res) throwsServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
// Use the connection uniquely assigned to this instance
Statement stmt = con.createStatement();
// Update the database any number of ways Commit the transaction
con.commit();
}
public void destroy() {
if (con != null)
con.close();
}
}