Unit 5
Unit 5
Introduction, Types of JDBC Drivers, Driver interface & DriverManager class, Connection Interface,
Statement Interface, PreparedStatement , ResultSet, JDBC Program for executing Statements & processing
ResultSet, Using PreparedStatement.
Java Database Connectivity (JDBC) is an application programming interface (API) for the Java
programming language which defines how Java applications interact with databases.
It is a Java-based data access technology used for Java database connectivity. It is part of the Java Standard
Edition platform, from Oracle Corporation.
It acts like a bridge between Java and databases, enabling Java programs to send SQL queries, retrieve data,
and perform database operations like inserting, updating, or deleting records. Java JDBC is oriented toward
relational databases.
Before JDBC, Java applications had no standard way to interact with databases. JDBC solves this by
providing:
• A standard API for communication with different databases.
• Independence from specific databases (MySQL, Oracle, PostgreSQL, etc.).
• Easy execution of SQL commands directly from Java.
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 Components
• 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 subprotocol 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.
• 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.
JDBC drivers are client-side adapters installed on the client machine rather than the server that translate
requests from Java programs into a protocol understood by the DBMS. These drivers are software
components that implement the interfaces in the JDBC API, allowing Java applications to interact with a
database.
They act as translators, converting JDBC calls into database-specific commands.
Sun has divided the implementation types into four categories:
▪ Type 1 : JDBC-ODBC Bridge Driver
▪ Type 2 : JDBC-Native API
▪ Type 3 : JDBC-Net pure Java
▪ Type 4 : 100% Pure Java
Type 1 : JDBC-ODBC Bridge Driver
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. Type-1 driver is also called
Universal driver because it can be used to connect to any of the databases. The type 1 driver requires ODBC
driver and DSN setup on each client machine. This performance of this driver is slow due tomultiple
translation layers. As it relies on native code it is not fully portable.
Type 3 JDBC drivers are referred to as middleware or network protocol drivers. They communicate with
the backend database using a specific networking protocol to query a server. The server then translates the
network protocol to the appropriate database call specific to the database storing the data. While the setup
and maintenance of the environments needed for Network Protocol Drivers can be complex, they are still
considered ideal for flexible, scalable applications. The flexibility comes from the fact that they do not need
any native binary code on their client environment. The Type-3 driveer are fully written in Java so they are
portable.
Type 4 : 100% Pure Java
Type 4 JDBC drivers is also called as Thin driver. It communicates directly with the source database, without
requiring any specific client installation or configuration. They are used by other applications to achieve
high-performance, direct-to-database interactions. It does not require any native library and middleware
server. It is platform independent as this driver is written in java language.
DriverManager Class
The DriverManager class in Java provides the basic service for managing a set of Java Database
Connectivity (JDBC) drivers. It maintains a list of database drivers.
The DriverManager class is part of the java.sql package. It is a singleton class. Only one instance of this
class is created in a JVM.
The DriverManager class acts as an interface between users and drivers.
It keeps track of the drivers that are available and handles establishing a connection between a database and
the appropriate driver.
It contains all the appropriate methods to register and deregister the database driver class and to create a
connection between a Java application and the database.
The DriverManager class is used as part of the JDBC API via the static getConnection() method.
• getConnection(String url, String user, String password): This accepts the database URL, username,
and password as parameters. It returns a Connection object that represents a connection to the given
database URL.
• deregisterDriver(Driver driver): This deregisters the given driver with the DriverManager class.
Drivers may be deregistered manually or automatically when they are no longer referenced.
• deregisterDrivers(): This deregisters all the currently-loaded drivers with the DriverManager class.
• getDriver(String url): This accepts the database URL. It returns a java.sql.Driver object that represents
the first driver from the list of loaded drivers that can connect to the given database URL.
• getDrivers(): This returns an enumeration of all loaded drivers.
Connection Interface
java.sql.Connection interface represents a session between java application and database. All SQL
statements are executed and results are returned with in the context of a Connection object.
Connection interface is mainly used to create java.sql.Statement, java.sql.PreparedStatement and
java.sql.CallableStatement objects.
It can also use it to retrieve the metadata of a database like name of the database product, name of the JDBC
driver, major and minor version of the database etc
Method Description
Statement Interface
A Statement object is used for executing a static SQL statement and obtaining the results produced by it.
The Statement interface in Java is part of the JDBC API and is used to execute static SQL queries and
updates (such as SELECT, INSERT, UPDATE, DELETE) against a relational database.
Statement object is created using Connection.createStatement() and execute SQL commands by passing
them as strings to methods like executeQuery() for queries and executeUpdate() for updates. The Statement
interface is best suited for executing simple, one-time SQL statements that do not require parameters. Each
Statement can have only one open ResultSet at a time; executing a new query closes the previous ResultSet.
Always close the Statement object after use to free up database resources.
A PreparedStatement in Java is a JDBC interface used to execute precompiled SQL statements with
parameter placeholders ("?") that can be set at runtime.
It is created using the Connection.prepareStatement() method, which sends the SQL statement to the
database for pre-compilation and storage.
You set parameter values using type-specific setter methods like setInt(), setString(), etc., before executing
the statement.
PreparedStatements can be executed multiple times with different parameter values, improving efficiency
and performance.
They help prevent SQL injection attacks by separating SQL code from data.
PreparedStatements are preferred over regular Statements for executing dynamic or repeated SQL queries
due to their security, performance, and ease of use.
ResultSet (I)
The SQL statements that read data from a database query, return the data in a result set. The SELECT
statement is the standard way to select rows from a database and view them in a result set. The
java.sql.ResultSet interface represents the result set of a database query. A ResultSet object maintains a
cursor that points to the current row in the result set. The term "result set" refers to the row and column data
contained in a ResultSet object. The cursor is movable based on the properties of the ResultSet. These
properties are designated when the corresponding Statement that generates the ResultSet is created.
The methods of the ResultSet interface can be broken down into three categories −
▪ Navigational methods: Used to move the cursor around.
▪ Get methods: Used to view the data in the columns of the current row being pointed by the cursor.
▪ Update methods: Used to update the data in the columns of the current row.
Methods of ResultSet
public void beforeFirst() throws SQLException Moves the cursor just before the first row.
public void afterLast() throws SQLException Moves the cursor just after the last row.
public boolean first() throws SQLException Moves the cursor to the first row.
public void last() throws SQLException Moves the cursor to the last row.
public boolean absolute(int row) throws SQLException Moves the cursor to the specified
row.
public boolean relative(int row) throws SQLException Moves the cursor the given number
of rows forward or backward, from where it is currently pointing.
public boolean previous() throws SQLException Moves the cursor to the previous row. This
method returns false if the previous row is off the result set.
public boolean next() throws SQLException Moves the cursor to the next row. This method
returns false if there are no more rows in the result set.
public int getRow() throws SQLException Returns the row number that the cursor is
pointing to.
The ResultSet interface contains dozens of methods for getting the data of the current row.
There is a get method for each of the possible data types, and each get method has two versions −
• One that takes in a column name.
• One that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to use one of the getInt()
methods of ResultSet −
S.N. Methods & Description
public int getInt(String columnName) throws SQLException
1
Returns the int in the current row in the column named columnName.
public int getInt(int columnIndex) throws SQLException
2 Returns the int in the current row in the specified column index. The column index starts at 1,
meaning the first column of a row is 1, the second column of a row is 2, and so on.
Java Program for Database Connectivity
package jdbcdemo;
import java.sql.*;
try
//Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url,username,password);
System.out.println("Connection Successful");
catch ( SQLException e) {
System.out.println(e.getMessage());
}
Program to Create Table in database
package jdbcdemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
class CreateDemo
{
public void createTable(Connection con)
{
Statement st = null;
try {
st = con.createStatement();
String creattable = "create table Empp (" + "id int," + "name varchar(50)"+")";
st.executeUpdate(creattable);
System.out.println("Table Created");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class JdbcCreateTableDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String url ="jdbc:mysql://localhost:3306/demo";
String username = "root";
String password = "Vinay@2006";
Connection con = null;
CreateDemo demo = new CreateDemo();
try
{
//Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url,username,password);
System.out.println("Connection Successful");
demo.createTable(con);
}
catch ( SQLException e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
Program to insert row in database table
package jdbcdemo;
import java.sql.*;
class InsertRow {
public void insertdata(Connection con) {
Statement st = null;
try {
st = con.createStatement();
String insertsql = "insert into empp(id,name) values(2,'sswpc')";
st.executeUpdate(insertsql);
System.out.println("Row Successfully inserted");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class InsertDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/demo";
String username = "root";
String password = "Vinay@2006";
Connection con = null;
InsertRow demo = new InsertRow();
try {
con = DriverManager.getConnection(url, username, password);
System.out.println("Connection Successful");
demo.insertdata(con);
} catch (SQLException e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
Program to update row in database table
package jdbcdemo;
import java.sql.*;
class UpdateRow
{
public void updateRow(Connection con)
{
Statement st = null;
try {
st = con.createStatement();
String updatesql = "update empp set name='sswp' where id=2";
st.executeUpdate(updatesql);
System.out.println("Row Successfully updated");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class UpdateData {
public static void main(String[] args) {
String url ="jdbc:mysql://localhost:3306/demo";
String username = "root";
String password = "Vinay@2006";
Connection con = null;
UpdateRow demo = new UpdateRow();
try
{
//Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url,username,password);
System.out.println("Connection Successful");
demo.updateRow(con);
}
catch ( SQLException e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
Program to fetch rows from database table
package jdbcdemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class FetchRows {
public void getData(Connection con) {
Statement st = null;
ResultSet rs = null;
String fetch = "Select * from empp";
try {
st = con.createStatement();
rs = st.executeQuery(fetch);
while(rs.next())
{
int id = rs.getInt(1);
String name = rs.getString(2);
System.out.println("ID is "+ id + " and name is "+name);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class SelectDataDemo {
package jdbcdemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
class DeleteDataDemo
{
public void deleteRow(Connection con)
{
Statement st = null;
try {
st = con.createStatement();
String del = "Delete from empp where id=2";
st.executeUpdate(del);
System.out.println("Deleted,......");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class DeleteData {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/demo";
String usrnm = "root";
String pswd = "Vinay@2006";
Connection connection = null;
DeleteDataDemo dm = new DeleteDataDemo();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(url,usrnm,pswd);
System.out.println("Connection is Successful");
dm.deleteRow(connection);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}
Prepared Statement Program (Insert , Update, Delete, Select queries)
package jdbcdemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
class InsertPreparedStatement
{
ResultSet rs= null;
public void insertData(Connection con)
{
PreparedStatement st = null;
try {
st = con.prepareStatement(insertsql);
st.setInt(1, 103);
st.setString(2, "Pune");
st.executeUpdate();
st.setInt(1, 3);
st.setString(2, "SSEMHS");
st.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteData(Connection con)
{
PreparedStatement st = null;
try {
st = con.prepareStatement(deletesql);
st.setInt(1, 103);
st.executeUpdate();
System.out.println("Row deleted..");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateData(Connection con)
{
PreparedStatement st = null;
try {
st = con.prepareStatement(updatesql);
st.setString(1, "Nagpur");
st.setInt(2, 103);
st.executeUpdate();
System.out.println("Row updated");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void selectData(Connection con)
{
PreparedStatement st = null;
try {
st = con.prepareStatement(selectsql);
st.setInt(1, 103);
rs = st.executeQuery();
System.out.println("Row fetched");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class PreparedStatementsDemo {