0% found this document useful (0 votes)
4 views

Chapter- 7 Database

JDBC (Java Database Connectivity) is a Java API that allows access to tabular data in relational databases across various platforms. It includes packages and interfaces for connecting to databases, executing SQL statements, and managing results. The document also outlines the steps to create a JDBC application, including driver registration, connection establishment, and executing SQL commands.

Uploaded by

wassiefikadu2121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter- 7 Database

JDBC (Java Database Connectivity) is a Java API that allows access to tabular data in relational databases across various platforms. It includes packages and interfaces for connecting to databases, executing SQL statements, and managing results. The document also outlines the steps to create a JDBC application, including driver registration, connection establishment, and executing SQL commands.

Uploaded by

wassiefikadu2121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Chapter-Seven

Java Database Connectivity(JDBC)


BY:
Andargie Mekonnen
What is JDBC?
JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database.

JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX.

JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of databases.

The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
Applications of JDBC
Java can be used to write different types of executables, such as :

Java Applications

Java Applets

Java Servlets

Java ServerPages (JSPs)

Enterprise JavaBeans (EJBs).


The JDBC Packages
The java.sql and javax.sql are the primary packages for JDBC . It offers the main classes
for interacting with your data sources.
The new features in these packages include changes in the following areas :
Automatic database driver loading.
Exception handling improvements.
Enhanced BLOB/CLOB functionality.
Connection and statement interface enhancements.
National character set support.
SQL ROWID access.
SQL 2003 XML data type support.
Annotations.
Interfaces and Classes of JDBC API
Following is the list of mostly used interfaces and classes in JDBC API.
DriverManager class − used to load a SQL driver to connect to database.
Connection interface − used to make a connection to the database using database connection
string and credentials.
Statement interface − used to make a query to the database.
PreparedStatement interface − used for a query with placeholder values.
CallableStatement interface − used to called stored procedure or functions in database.
ResultSet interface − represents the query results obtained from the database.
ResultSetMetaData interface − represents the metadata of the result set.
BLOB class −represents binary data stored in BLOB format in database table.
CLOB class −represents text data like XML stored in database table
Types of API in JDBC
JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into
four categories, Types 1, 2, 3, and 4, which is explained below −
Type 1 − a JDBC bridge is used to access ODBC drivers installed on each client
machine. For example, JDBC-ODBC Bridge driver in JDK 1.2.
Type 2 − JDBC API calls are converted into native C/C++ API calls, which are unique
to the database. These APIs are vendor specific and vendor provided driver is required
to be installed. It is also called JDBC Native API. For example, Oracle Call Interface
(OCI) driver.
Types of API in JDBC
Type 3 − A three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The
socket information is then translated by the middleware application server into the call
format required by the DBMS, and forwarded to the database server. It is also called
JDBC-Net Pure Java driver.
Type 4 − A pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the
database and is usually provided by the vendor itself. For example, MySQL's
Connector/J driver to connect to MySQL database.
Which Driver should be Used?
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the
preferred driver type is 4.
If your Java application is accessing multiple types of databases at the same
time, type 3 is the preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not
available yet for your database.
The type 1 driver is not considered a deployment-level driver, and is typically
used for development and testing purposes only.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for
database access but in general, JDBC Architecture consists of two layers
JDBC API − This provides the application-to-JDBC Manager connection.
JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access
each data source. The driver manager is capable of supporting multiple
concurrent drivers connected to multiple heterogeneous databases.
JDBC Architecture
Following is the architectural diagram, which shows the location of the driver
manager with respect to the JDBC drivers and the Java application :
Common JDBC Components
The JDBC API provides the following interfaces and classes :

DriverManager − This class manages a list of database drivers. Matches connection


requests from the java application with the proper database driver using
communication sub protocol. The first driver that recognizes a certain sub protocol
under JDBC will be used to establish a database Connection.

Driver − This interface handles the communications with the database server. You
will interact directly with Driver objects very rarely. Instead, you use DriverManager
objects, which manages objects of this type. It also abstracts the details associated
with working with Driver objects.
Common JDBC Components
Connection − This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication with
database is through connection object only.

Statement − You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in addition to
executing stored procedures.

ResultSet − These objects hold data retrieved from a database after you execute an
SQL query using Statement objects. It acts as an iterator to allow you to move
through its data.

SQLException − This class handles any errors that occur in a database application.
Creating JDBC Application
There are following six steps involved in building a JDBC application:
Import the packages − Requires that you include the packages containing the JDBC classes
needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create
Connection object, which represents a physical connection with the database.
Execute a query − Requires using an object of type Statement for building and submitting an
SQL statement to the database.
Extract data from result set − Requires that you use the appropriate ResultSet.getXXX()
method to retrieve the data from the result set.
Clean up the environment − Requires explicitly closing all database resources versus relying
on the JVM's garbage collection.
Creating JDBC Application
Import JDBC Packages
The Import statements tell the Java compiler where to find the classes you reference in
your code and are placed at the very beginning of your source code.
To use the standard JDBC package, which allows you to select, insert, update, and delete
data in SQL tables, add the following imports to your source code −
import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
Creating JDBC Application
Register JDBC Driver
Registering the driver is the process by which the Oracle driver's class file is loaded into
the memory, so it can be utilized as an implementation of the JDBC interfaces.
You need to do this registration only once in your program. You can register a driver in one
of two ways.
Approach I - Class.forName()
The most common approach to register a driver is to use Java's Class.forName()
method, to dynamically load the driver's class file into memory, which automatically
registers it. This method is preferable because it allows you to make the driver
registration configurable and portable.
Creating JDBC Application
Register JDBC Driver
The following example uses Class.forName( ) to register the Oracle driver :
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
System.out.println(con);
System.out.println("database is conneected");
} catch (ClassNotFoundException ex) {
Logger.getLogger(ConnectMYSQL.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ConnectMYSQL.class.getName()).log(Level.SEVERE, null, ex);
}
}

}
Creating JDBC Application
Register JDBC Driver
Approach II - DriverManager.registerDriver()
The second approach you can use to register a driver, is to use the static
DriverManager.registerDriver() method.
You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as
the one provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver:
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1); }
Creating JDBC Application
Database URL Formulation
After you've loaded the driver, you can establish a connection using the
DriverManager.getConnection() method. For easy reference, let me list the three
overloaded DriverManager.getConnection() methods :
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to your
database.
Formulating a database URL is where most of the problems associated with establishing a
connection occurs.
Creating JDBC Application
Following table lists down the popular JDBC driver names and database URL.
All the highlighted part in URL format is static and you need to change only the
remaining part as per your database setup.
Creating JDBC Application
Create Connection Object
We have listed down three forms of DriverManager.getConnection() method to create a
connection object.
Using a Database URL with a username and password
The most commonly used form of getConnection() requires you to pass a database
URL, a username, and a password
Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName
value for the database portion of the URL.
Creating JDBC Application
If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your
Oracle listener is configured to listen on port 1521, and your database name is EMP,
then complete database URL would be : jdbc:oracle:thin:@amrood:1521:EMP

Now you have to call getConnection() method with appropriate username


and password to get a Connection object as follows:
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Creating JDBC Application
Using Only a Database URL
A second form of the DriverManager.getConnection( ) method requires only a database
URL :
DriverManager.getConnection(String url);
However, in this case, the database URL includes the username and password and has
the following general form : jdbc:oracle:driver:username/password@database
So, the above connection can be created as follows :
String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP";
Connection conn = DriverManager.getConnection(URL);
Creating JDBC Application
Using a Database URL and a Properties Object
A third form of the DriverManager.getConnection( ) method requires a database URL
and a Properties object : DriverManager.getConnection(String url, Properties info);
A Properties object holds a set of keyword-value pairs. It is used to pass driver
properties to the driver during a call to the getConnection() method.
To make the same connection made by the previous examples, use the following code :
import java.util.*;
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );
Connection conn = DriverManager.getConnection(URL, info);
Creating JDBC Application
Closing JDBC Connections
At the end of your JDBC program, it is required explicitly to close all the connections to
the database to end each database session. However, if you forget, Java's garbage collector
will close the connection when it cleans up stale objects.
Relying on the garbage collection, especially in database programming, is a very poor
programming practice. You should make a habit of always closing the connection with the
close() method associated with connection object.
To ensure that a connection is closed, you could provide a 'finally' block in your code. A
finally block always executes, regardless of an exception occurs or not.
To close the above opened connection, you should call close() method as follows :
conn.close();
Creating JDBC Application
JDBC - 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.
Creating JDBC Application
The following table provides a summary of each interface's purpose to decide on the
interface to use.
Creating JDBC Application
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 {
...
}
Creating JDBC Application
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.
Creating JDBC Application
Closing 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.
Statement stmt = null;
try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
stmt.close();
}
Creating JDBC Application
The PreparedStatement Objects
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.
All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. You must
supply values for every parameter before executing the SQL statement
Creating PreparedStatement Object
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
..}
Creating JDBC Application
The CallableStatement Objects
Just as a Connection object creates the Statement and PreparedStatement objects, it also
creates the CallableStatement object, which would be used to execute a call to a database
stored procedure .
Suppose, you need to execute the following Oracle stored procedure :
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;
Creating JDBC Application
NOTE − Above stored procedure has been written for Oracle, but we are working with
MySQL database so, let us write same stored procedure for MySQL as follows to create it
in EMP database :
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$

DELIMITER ;
Creating JDBC Application
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only
uses the IN parameter. The CallableStatement object can use all the three.

Parameter Description

A parameter whose value is unknown when the SQL statement is


IN created. You bind values to IN parameters with the setXXX()
methods.
A parameter whose value is supplied by the SQL statement it
OUT returns. You retrieve values from theOUT parameters with the
getXXX() methods.
A parameter that provides both input and output values. You bind
INOUT variables with the setXXX() methods and retrieve values with the
getXXX() methods.
Creating JDBC Application
The following code snippet shows how to employ the Connection.prepareCall() method to
instantiate a CallableStatement object based on the preceding stored procedure −
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
. . .}
Creating JDBC Application
The String variable SQL, represents the stored procedure, with parameter placeholders.
Using the CallableStatement objects is much like using the PreparedStatement objects. You
must bind values to all the parameters before executing the statement, or you will receive an
SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setXXX() method that corresponds to the Java data type
you are binding.
Creating JDBC Application
When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The registerOutParameter() method
binds the JDBC data type, to the data type that the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter with
the appropriate getXXX() method. This method casts the retrieved value of SQL type to a
Java data type.
Creating JDBC Application
Closing CallableStatement Object
Just as you close other Statement object, for the same reason you should also close the
CallableStatement object.
A simple call to the close() method will do the job. If you close the Connection object first, it will
close the CallableStatement object as well. However, you should always explicitly close the
CallableStatement object to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
cstmt.close();}
Creating JDBC Application
Closing CallableStatement Object
Just as you close other Statement object, for the same reason you should also close the
CallableStatement object.
A simple call to the close() method will do the job. If you close the Connection object first, it will
close the CallableStatement object as well. However, you should always explicitly close the
CallableStatement object to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
cstmt.close();}
Creating JDBC Application Example:
import java.sql.*; {
public class SelectExample { // Extract data from result set
static final String DB_URL = while (rs.next()) {
"jdbc:mysql://localhost/TUTORIALSPOINT"; // Retrieve by column name
static final String USER = "guest"; System.out.print("ID: " + rs.getInt("id"));
static final String PASS = "guest123"; System.out.print(", Age: " +
static final String QUERY = "SELECT id, first, last, rs.getInt("age"));
age FROM Employees"; System.out.print(", First: " +
public static void main(String[] args) { rs.getString("first"));
// Open a connection System.out.println(", Last: " +
try(Connection conn = rs.getString("last"));
DriverManager.getConnection(DB_URL, USER, }
PASS); } catch (SQLException e) {
Statement stmt = conn.createStatement(); e.printStackTrace();
ResultSet rs = stmt.executeQuery(QUERY);) { }
}
}
Creating JDBC Application Example:
In this example, we've four static strings containing a dababase connection url, username,
password and a SELECT query.

Now using DriverManager.getConnection() method, we've prepared a database connection.

Once connection is prepared, we've created a Statement object using


connection.createStatement() method, then using statement.executeQuery(), the SELECT
Query is executed and result is stored in a resultset.

Now resultset is iterated and each record is printed.


Creating JDBC Application Example:
In this example, we've four static strings containing a dababase connection url, username,
password and a SELECT query.

Now using DriverManager.getConnection() method, we've prepared a database connection.

Once connection is prepared, we've created a Statement object using


connection.createStatement() method, then using statement.executeQuery(), the SELECT
Query is executed and result is stored in a resultset.

Now resultset is iterated and each record is printed.

You might also like