0% found this document useful (0 votes)
24 views40 pages

Unit 4 JDBC

This document provides an overview of JDBC (Java Database Connectivity), including its architecture, driver types, and key components for connecting Java applications to databases. It covers practical aspects such as executing SQL commands, using JDBC classes and interfaces, and connecting to MySQL databases with example code. Additionally, it discusses the advantages and disadvantages of different JDBC driver types and includes instructions for setting up a database and performing CRUD operations.

Uploaded by

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

Unit 4 JDBC

This document provides an overview of JDBC (Java Database Connectivity), including its architecture, driver types, and key components for connecting Java applications to databases. It covers practical aspects such as executing SQL commands, using JDBC classes and interfaces, and connecting to MySQL databases with example code. Additionally, it discusses the advantages and disadvantages of different JDBC driver types and includes instructions for setting up a database and performing CRUD operations.

Uploaded by

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

Unit IV Database Programming using JDBC (6 Hrs)

 The Concepts of JDBC, JDBC Driver Types & architecture, JDBC


Packages, A Brief Overview of the JDBC Process, Database
Connection, Connecting to non-conventional Databases Java
Databased Client/server, Basic JDBC program concept, Statement,
Resultset, prepared Statement, Callable Statement, Executing SQL
Commands, Executing queries

1
Advance Java Books : Books
TEXT BOOKS
Jim Keogh, “Complete Reference J2EE”, Enterpr

REFERENCE BOOKS
Java Server Programming, Java EE6 (J2EE 1.6) Black book, dreamtech
M.T. Savaliya, “Advanced Java Technology”, dreamtech

ADDITIONAL MATERIAL
MOOC / NPTEL:

2
Teaching Methodology: Topic – Book –
Pages/online site Mapping
Reference / text book
Sr. No. Topic
with page
no./web
refrence
UNIT number: name

3
JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java application
programming interfaces (API) to connect and execute the query with
the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses
JDBC drivers to connect with the database. There are four types of JDBC
drivers:

1. JDBC-ODBC(Open Database Connectivity) Bridge Driver,


2. Native Driver,
3. Network Protocol Driver, and
4. Thin Driver

4
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open Database
Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based
on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for
JDBC API. A list of popular interfaces of JDBC API are given below:

 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface
A list of popular classes of JDBC API are given below:
 DriverManager class
 Blob class (Binary Large Object)
 Clob class (Character Large Object)
 Types class
Why JDBC?
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC
drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following
activities:
 Connect to the database
 Execute queries and update statements to the database
 Retrieve the result received from the database.
What is API?
API (Application programming interface) is a
document that contains a description of all the
features of a product or software. It represents
classes and interfaces that software programs can
follow to communicate with each other. An API can
be created for applications, libraries, operating
systems, etc.
JDBC Driver Types and Architecture
JDBC Driver is a software component that enables java
application to interact with the database. There are 4 types
of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
JDBC-ODBC Bridge Driver
The 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. This is now discouraged
because of thin driver. Note: In Java 8, the JDBC-ODBC Bridge has been removed.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that
you use JDBC drivers provided by the vendor of your database instead of the JDBC-
ODBC Bridge.
Advantages:
 easy to use.
 can be easily connected to any database.
Disadvantages:
 Performance degraded because JDBC method call is converted into the ODBC
function calls.
 The ODBC driver needs to be installed on the client machine.
Native-API Driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.
Advantage:
 Performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
 The Native driver needs to be installed on the each client machine.
 The Vendor client library needs to be installed on client machine.
Network Protocol Driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
 No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
 Network support is required on client machine.
 Requires database-specific coding to be done in the middle tier.
 Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
Thin Driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.
Advantage:
 Better performance than all other drivers.
 No software is required at client side or server side.
Disadvantage:
 Drivers depend on the Database.
JDBC Architecture
A JDBC Driver is required to process the
SQL requests and generate results. JDBC
API provides classes and interfaces to
handle database-specific calls from users.
As shown in fig, the Java Application that
needs to communicate with a database
has to be programmed using JDBC API.
The JDBC driver supporting data source,
such as Oracle, SQL has to added in the
Java Application for the JDBC Support,
which can be done dynamically at run-
time.
JDBC Packages
JDBC API is mainly divided into following two packages,
 java.sql
 javax.sql

These two packages are included in J2SE and are even available to the J2EE Platform.
java.sql
1. Making a connection with a database via the DriverManager facility
o DriverManager class -- makes a connection with a driver
o SQLPermission class -- provides permission when code running within a Security
Manager, such as an applet, attempts to set up a logging stream through the
DriverManager
o Driver interface -- provides the API for registering and connecting drivers based on
JDBC technology ("JDBC drivers"); generally used only by the DriverManager class
o DriverPropertyInfo class -- provides properties for a JDBC driver; not used by the
general user
2. Sending SQL statements to a database
o Statement -- used to send basic SQL statements
o PreparedStatement -- used to send prepared statements or basic SQL statements
(derived from Statement)
o CallableStatement -- used to call database stored procedures (derived from
PreparedStatement)
o Connection interface -- provides methods for creating statements and managing
connections and their properties
o Savepoint -- provides savepoints in a transaction
3. Retrieving and updating the results of a query
o ResultSet interface
4. Standard mappings for SQL types to classes and interfaces in the Java programming
language
o Array interface -- mapping for SQL ARRAY
o Blob interface -- mapping for SQL BLOB
o Clob interface -- mapping for SQL CLOB(Character Large Object value)
o Date class -- mapping for SQL DATE
o NClob interface -- mapping for SQL NCLOB(National Character Large Object)
o Ref interface -- mapping for SQL REF
o Rowid interface -- mapping for SQL ROWID(Oracle uses a ROWID datatype to store the
address (rowid) of every row in the database.)
o Struct interface -- mapping for SQL STRUCT
o SQLXML interface -- mapping for SQL XML
o Time class -- mapping for SQL TIME
o Timestamp class -- mapping for SQL TIMESTAMP
o Types class -- provides constants for SQL types
5. Exceptions
 SQLException -- thrown by most methods when there is a problem
accessing data and by some methods for other reasons
 SQLWarning -- thrown to indicate a warning
 DataTruncation -- thrown to indicate that data may have been
truncated
 BatchUpdateException -- thrown to indicate that not all commands in a
batch update executed successfully
javax.sql
The javax,sql package is also called as the JDBC extension API, and provides
classes and interfaces to access server-side data sources and process Java
Programs. The JDBC extension package supplements the java.sql package and
provide the following support,
 DataSource
 Connection and Statement Pooling
 Distributed transaction
 Rowsets
Java Database Connectivity with MySQL
To connect Java application with the MySQL database, we need to follow 5 following steps.

In this topic, we are using MySql as the database. So we need to know following information's
for the mysql database:
 Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver

 Connection URL: The connection URL for the mysql database is


jdbc:mysql://localhost:3306/sppu where jdbc is the API, mysql is the database, localhost is
the server name on which mysql is running, we may also use IP address, 3306 is the port
number and sppu is the database name. We may use any database, in such case, we need to
replace the sppu with our database name.
 Username: The default username for the mysql database is root.

 Password: It is the password given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.
Lets Create a Database and Tables
 mysql -u root -p
 Enter password as root
 Show databases;
 create database sppu;
 use sppu;
 Show tables;
 create table info (name varchar(100) not null, email varchar(50), city varchar(50));
 insert into info values (‘Ganesh’,’[email protected]’,’Nashik’);
 select * from info;
SQL Queries
• SELECT column1, column2, ... FROM table_name;
• SELECT column1, column2, ... FROM table_name WHERE condition;
• INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
• INSERT INTO table_name VALUES (value1, value2, value3, ...);
• UPDATE table_name SET column1 = value1, column2 = value2, ...
WHERE condition;
• DELETE FROM table_name WHERE condition;
VIMP Classes in Practicals
 DriverManager Class: 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.
 Connection Interface: A Connection is a session between a Java application and a
database. It helps to establish a connection with the database. The Connection
interface is a factory of Statement, PreparedStatement.
 Statement Interface: The Statement interface provides methods to execute queries
with the database. The statement interface is a factory of ResultSet i.e. it provides
factory method to get the object of ResultSet.
 ResultSet Interface: The object of ResultSet maintains a cursor pointing to a row of a
table. Initially, cursor points to before the first row.
 PreparedStatement Interface: The PreparedStatement interface is a subinterface of
Statement. It is used to execute parameterized query.
Practical Time
We can use Notepad as editor and command line to execute our code.
To Compile a code
javac ClassFileName.java
To run code from command line,
java -cp .;D:\mysql-connector.jar ClassFileName

OR

We can use eclipse IDE to write and execute our code.


import java.sql.*;
public class FirstJDBCProgram{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sppu","root","root");

Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(“Success”);
con.close();
}catch(Exception e){
System.out.println(e);}
}
}
08/18/2025 32
Download mysql-connector.jar
https://static.javatpoint.com/src/jdbc/mysql-connector.jar

Or same will be provided through Google Drive.


To add this to eclipse java project,
 Right click on Project and go to properties
 Click on Java Build Path -> Libraries -> Classpath -> Add External JARs
 Provide the path of mysql-connector.jar file and click on Open
 Click Apply and Close
Still getting Error?
In case if you get ERROR as
java.sql.SQLException: Unknown initial character set index ‘255’ received from
server.

Then change connection url as


Before: "jdbc:mysql://localhost:3306/sppu"
After: "jdbc:mysql://localhost:3306/sppu?characterEncoding=latin1”

You then try one more time.


import java.sql.*;
public class SQLStatementSelect{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/logininfo?characterEncoding=latin1","root","root");

Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from userinfo");
while(rs.next())
{
//System.out.println("Success");
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3) + " " +
rs.getString(4) );
}
con.close();
}catch(Exception e){ System.out.println(e);}
08/18/2025
} 35
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLPreparedStatementInsert {

public static void main(String[] args) {


try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/logininfo?characterEncoding=latin1","root","root");

PreparedStatement stmt = con.prepareStatement("insert into userinfo values (?,?,?,?)");


stmt.setString(1,"user3");
stmt.setString(2,"pass3");
stmt.setString(3,"[email protected]");
stmt.setString(4, "India");
//stmt.setString(4,"India");
int i = stmt.executeUpdate();
System.out.println(i + "Records inserted..");
con.close();
}
catch(Exception e){
System.out.println(e);
}

08/18/2025 } 36
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class SQLPreparedStatementUpdate {


public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/logininfo?characterEncoding=latin1","root","root");

PreparedStatement stmt = con.prepareStatement("update userinfo set email=? where username=?");


stmt.setString(1,"[email protected]");
stmt.setString(2,"user1");

int i = stmt.executeUpdate();
System.out.println(i + "Records updated");
con.close();
}
catch(Exception e){
System.out.println(e);
}
08/18/2025 } 37
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class SQLPreparedStatementDelete {

public static void main(String[] args) {


try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/logininfo?characterEncoding=latin1","root","root");

PreparedStatement stmt = con.prepareStatement("delete from userinfo where username=?");


stmt.setString(1,"user2");

int i = stmt.executeUpdate();
System.out.println(i + "Records deleted");
con.close();
}
catch(Exception e){
System.out.println(e);
}
08/18/2025 } 38
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class SQLPreparedStatementSelect {


public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/logininfo?characterEncoding=latin1","root","root");

PreparedStatement stmt = con.prepareStatement("select * from userinfo");


ResultSet rs = stmt.executeQuery();
while(rs.next())
{
System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " +
rs.getString(4) + " ");

}
con.close();
}
catch(Exception e){ System.out.println(e); }
08/18/2025 } 39
Additional Online available Link/
Reference books
 https://www.javatpoint.com/java-jdbc
 https://www.w3schools.com/sql/

You might also like