0% found this document useful (0 votes)
285 views50 pages

JDBC Connection in Java

jdbc connection in java

Uploaded by

anuja_java
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
285 views50 pages

JDBC Connection in Java

jdbc connection in java

Uploaded by

anuja_java
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 50

Database access using Servlets

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.
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
JDBC drivers

• Drivers are libraries used by applications to connect to databases.


• The JVM uses the JDBC driver to translate generalized JDBC calls
into vendor specific database calls.
• JDBC drivers implement some of the JDBC API
Types of JDBC Driver
• Type 1: JDBC-ODBC Bridge
•  Type 2: Part Java, Part Native Driver
• Type 3: Intermediate database Access Server
• Type 4: Pure Java Drivers
ODBC ODBC
Type I Data
“Bridge” API Layer Source

Native Code Data


Type II
Library Source
“Native”
JDBC
Type III Middleware Data
“Middleware” Server Source

Type IV Data
“Pure” Source
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, that
interfaces the Java Virtual Machine to ODBC.
Server Data
Java Application Client
Source

JDBC JDBC-ODBC
ODBC ODBC
API Bridge
API Layer

• 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
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 use
the 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.
Contd..
Disadvantages
• Slow
 JDBC call goes thru’ the bridge to the ODBC driver then to database-
specific driver.
• Native code required
• Data source to be defined on each client machine
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 databases such as
SQL server, Oracle, Sybase etc
• e.g. Oracle Driver, WebLogic drivers
Java Application Client

Server

JDBC Vendor
JDBC Driver
API API
Data
Source

Part Java, Part Native Driver


Contd..
Advantage
• Type 2 drivers typically offer significantly better performance than 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 the Internet.
• Type 2 drivers show lower performance than type 3 and type 4
drivers.
Application
Standalone GUI- intensive program that always runs on NT may use
Type 2 native code driver.
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 type of driver
to provide actual database access.
• Type 3 JDBC drivers are pure Java drivers for database
middleware.
• e.g. Symantec
Server
Java Client
Application
Data
Source

JDBC
JDBC Driver JDBC Driver Native
API
Server Driver

•JDBC calls are translated into a middleware vendor's protocol, and the
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 makes Type 3 drivers faster
than Type 1 and Type 2 drivers.
•Developers can also use a single JDBC driver to connect to multiple
databases.
Contd..

Advantages:
• Pure Java. No native code to be installed on client machine.
• Flexible when client wants to communicate with multiple databases
from 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 the
middle tier.
• Slow- presence of gateway. Gateway reads data from database then
sends to client.
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-specific
networking protocols by making direct connections with database
• They understand database-specific networking protocols and can access
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 this
is outweighed by the fact that Type 4 drivers provide faster
performance and direct access to DBMS features.
• e.g. Oracle, mySQL
Server
Java Client
Application
Data
Source

JDBC
API JDBC Driver

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
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.
Driver Statement Connection ResultSet ResultSetMetaD DatabaseMeta
ata Data
PreparedStatement

CallableStatement
java.lang.Object

java.util.date DriverManager DriverPropertyInfo Types

Date Time TimeStamp


Interfaces
Driver
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 and
then for any given connection request, it will ask each driver in turn to
try to connect to the target URL.
• When a Driver class is loaded, it should create an instance of itself and
register it with the DriverManager. This means that a user can load
and register a driver by calling
Class.forName("foo.bah.Driver")
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
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.
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.
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
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.
Contd..
DatabaseMetaData
• Provides information on the database as a whole
• What tables are available?
• Is the database in read-only mode?
Classes
DriverManager
• This is a very important class.
• Its main purpose is to provide a means of managing the
different types of JDBC database driver
• On running an application, it is the DriverManager's
responsibility to load all the drivers found in the system
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
Code JDBC
import
SQL
java.sql.*; Utilities Driver DB
class useDB
{
} Connectivity
Driver Connection Statement ResultSet
Manager

SQL Data

Driver

Database
 
DriverManager
• Used to provide common access layer on the top of different database
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 the DriverManager is aware of it
getConnection(“jdbc:odbc:myLib”)
Sybase Driver

Driver Manager
Oracle Driver

Connection
JDBC ODBC Driver
Driver Manager
• 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 the URL 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
How to load Driver Manager
• 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 class
forName
public static Class forName(String className) throws ClassNotFoundException
Connecting to a Database
• The Connection represents a single logical database transaction.
• The Connection Interface has methods for sending a series of SQL 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();
}
 
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();
}
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();
 
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 * FROM ells"); 
ResultSet result = stat.executeQuery("SELECT name, cups FROM
JoltData ORDER BY cups DESC;");
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 statement executions will
return a value greater than or equal to zero, which is the number of
tuples affected in the relation
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 data
stat.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");
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");
}
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 in the second
form the position of that column in the table is specified.
• Retrieving a result by index is faster than retrieving a result by column
name. But the disadvantage is that the code is harder to maintain.
• 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());
 
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); }
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();
}
}
}
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 instance
public void init(ServletConfig config) throws ServletException{
super.init(config);
// Establish the connection for this instance
con = establishConnection();
con.setAutoCommit(false);
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, 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();
}
}
 

You might also like