Module-4
JDBC
What is SQL?
• SQL stands for Structured Query Language.
• SQL lets you access and manipulate databases.
• SQL became a standard of the American National Standards
Institute (ANSI) in 1986, and of the International
Organization for Standardization (ISO) in 1987.
What Can SQL do?
• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a database
• SQL can create views in a database
• SQL can set permissions on tables, procedures, and views
SQL Statements
• Most of the actions you need to perform on a database are
done with SQL statements.
• SQL statements consist of keywords that are easy to
understand.
• The following SQL statement returns all records from a table
named "Customers“
• Select all records from the Customers table:
SELECT * FROM Customers;
Some of The Most Important SQL
Commands
•SELECT - extracts data from a database
•UPDATE - updates data in a database
•DELETE - deletes data from a database
•INSERT INTO - inserts new data into a database
•CREATE DATABASE - creates a new database
•ALTER DATABASE - modifies a database
•CREATE TABLE - creates a new table
•ALTER TABLE - modifies a table
•DROP TABLE - deletes a table
•CREATE INDEX - creates an index (search key)
•DROP INDEX - deletes an index
• SQL is used to access and manipulate data in databases.
• We can create, update, delete, and retrieve data in databases
like MySQL, Oracle, PostgreSQL, etc.
• SQL is a query language that communicates with databases.
SQL Uses
• SQL's integration with various technologies makes it essential for managing and querying data
in databases.
• Whether it's in traditional relational databases (RDBMS) or modern technologies such as machine
learning, AI, and blockchain, SQL plays a key role.
• It works seamlessly with DBMS to help users interact with data, whether stored in
structured RDBMS or other types of databases.
• Data Science & Analytics: Used for querying large datasets, data cleaning, and analysis.
Analysts use SQL to generate reports and insights that inform business decisions.
• Machine Learning & AI: Helps in preparing and managing the data required for training
machine learning models and AI algorithms. It is used for data cleaning, transformation, and
extraction.
• Web Development: Used to manage user data, e-commerce transactions, and content
management in websites and applications built with frameworks like Django, Node.js, and Ruby on
Rails.
• Cloud and Big Data: SQL is integrated into cloud-based databases (e.g., Amazon RDS, Microsoft
Azure SQL) and Big Data platforms (e.g., Apache Hive) to enable seamless data querying and
management.
• Blockchain and Decentralized Systems: In blockchain systems, SQL can be used to manage
How SQL work?
• When you interact with a database, you typically use SQL commands to
perform the operations.
• These commands are translated into actions by the SQL Engine, the core
component responsible for processing queries.
• The SQL Engine parses and compiles SQL queries, optimizing and executing
them to interact with the stored data.
• The SQL Engine also ensures that data retrieval and modifications are efficient
and consistent.
• Different DBMS tools (MySQL, SQL Server) provide an interface and APIs that
users can use to interact with the database.
• These tools provide a user-friendly way to write and execute SQL queries, but
internally, they rely on their respective SQL Engines to process these
commands.
• For example, MySQL uses its own SQL Engine to parse, optimize, and execute
queries, while SQL Server has a different SQL Engine for the same task.
• These engines ensure that SQL queries are executed in a way that respects the
Example
Create a table to store employee information and populate it
with sample data
like Employee_Id, Name, Age, Department, and Salary.
Retrieve data from the employees table where the salary is
greater than 55000.00 then we will use SELECT Statement.
SELECT * FROM employees WHERE Salary > 55000.00;
Basics
• SQL is a fundamental skill for anyone who wants to interact
with databases.
• This standard Query Language allows all users to create,
manage, and retrieve data from relational databases.
Create Database
• The first step to storing the information electronically
using SQL includes creating database.
• CREATE Database
• DROP Database
• RENAME Database
• SELECT Database
What Is a Database?
• A database is a huge collection of data that is stored and
retrieved electronically from a system.
• The structured data stored in the database is processed,
manipulated, controlled, and updated to perform various
operations.
• Some of the popular databases used in the industries are
• Oracle
• MySQL
• PostgreSQL
• MS SQL Server
• SQLite
What Is SQL?
SQL is a standard programming language used to operate
Relational Databases and carry out various operations such as
inserting, manipulating, updating, and retrieving data from
relational databases.
Why Is SQL Required?
SQL is required for the following tasks
• To create new databases, tables, and views
• To insert records in a database
• To update records in a database
• To delete records from a database
• To retrieve data from a database
Applications of SQL
• SQL is used to create a database, define its structure, implement it,
and perform various functions on the database.
• SQL is also used for accessing, maintaining, and manipulating
already created databases.
• SQL is a well built language for entering data, modifying data, and
extracting data in a database.
• SQL is enormously used as a Client/Server language to connect the
front-end with the back-end, thus supporting the client/server
architecture.
• SQL when deployed as Data Control Language(DCL), helps protect
your database from unauthorized access.
Features of SQL
• SQL is used to access data within the relational database.
• SQL is very fast in extracting large amounts of data very efficiently.
• SQL is flexible as it works with multiple database systems from
Oracle, IBM, Microsoft, etc.
• SQL helps you manage databases without knowing a lot of coding.
Basic Queries in SQL
1) SHOW Statement
It lists the databases present on the MySQL Workbench server
host.
Syntax:
show databases;
• The following SQL query will show all the databases present on
MySQL Workbench server host.
2) USE Statement
The USE Statement selects a database and performs SQL operations
on that database.
The database remains default until the end of session or execution of
another USE statement with some other database.
Syntax:
USE database_name;
The following SQL query will let you perform operations on the
selected mysql database.
Use mysql;
3) CREATE TABLE Statement
The CREATE TABLE statement is used in SQL to create a new table.
Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype);
create table customers (Cust_Id int primary key, Cust_Name
varchar(25), Age int, Gender char(1), Dob date, Address varchar(20),
Item varchar(15), Price float);
);
• The following SQL query will create a customer table with attributes: customer id, customer name, age, gender, date of purchase, address, item, and price.
4) INSERT INTO Statement
• The INSERT INTO statement is basically used to add new data in a table.
• Syntax:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
The following SQL query will insert data into the records in the customers table.
insert into customers values (101, "Joseph", 22, "M", "2016-11-23", "Pune", "Vegetable", 80),
(120, "Illeana", 25, "F", "2016-11-23", "Chicago", "brinjal", 550),
(102, "Nilesh", 21, "M", "2016-11-23", "New York", "softdrink", 800),
(103, "Vipul", 33, "M", "2016-11-23", "Miami", "candies", 620);
5) SELECT Statement
• The most commonly used SQL command is the SELECT
statement.
• SQL SELECT statement is used to select rows and columns
from a table in the database.
Syntax:
SELECT column1, column2, ... FROM table_name;
The following SQL query will return all the records of the
customers table.
Select * from customers;
6) DROP TABLE Statement
• The DROP Statement is basically used to delete a particular table.
• Dropping of the table will drop all the objects (tables, views,
procedures, etc.) inside it.
• The user should have admin privileges for deleting a table.
Syntax:
DROP TABLE table_name;
The following SQL query will drop or delete the customers table
from the database.
Drop table customers;
7)TRUNCATE TABLE Statement
The TRUNCATE TABLE command deletes the data inside a table,
but not the table itself.
Syntax:
TRUNCATE TABLE Categories;
The following SQL query will delete all the records from the
customers table.
truncate table customers;
8) ALTER TABLE Statement
• ALTER TABLE command is used to update the structure of a
table by updating the definition of its columns.
• The ALTER command can perform the following functions:
1) Add, drop, modify table columns
2) Add and drop constraints
3) Enable and Disable constraints
Syntax:
ALTER TABLE table_name ADD column_name datatype;
The following SQL query will return the customers table without
an age column.
alter table customers drop column age;
9)DELETE Statement
A DELETE statement is used to delete fields from a table.
Syntax:
DELETE FROM table_name WHERE condition;
The following SQL query will delete the record with customer id
= 102.
delete from customers where Cust_Id=102;
10) UPDATE Statement
The UPDATE statement is basically used to update the existing
records in a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
The following SQL query will update the customer name to
James and city name as Boston in the record with customer id
= 101.
• update customers set Cust_Name = "James", Address=
"Boston" where Cust_Id = 101;
11) DISTINCT Statement
The SELECT DISTINCT statement in SQL is used to return only
unique values from a column.
Syntax:
SELECT DISTINCT column1, column2, ...
FROM table_name;
The following SQL query will return the unique cities where
customers reside.
• select distinct address from customers;
12) MIN() Function
The MIN() function returns the smallest value of the selected
numeric column in a table.
Syntax:
SELECT MIN(column_name) FROM table_name WHERE
condition;
The following SQL query will return the minimum price spent
by the customer.
select MIN(Price) AS LessPrice from customers;
13) MAX() Function
The MAX() function returns the largest value of the selected
numeric column.
Syntax:
SELECT MAX(column_name) FROM table_name WHERE
condition;
The following SQL query will return the maximum price spent by
the customer.
• select MAX(Price) AS MaxPrice from customers;
14) SUM Function
The SUM() function gives the total sum of a numeric column.
Syntax:
SELECT SUM(column_name) FROM table_name WHERE
condition;
The following SQL query will return the sum of the price spent
by the customers.
select SUM(Price) from customers;
15) AVG() Function
The AVG() function gives the average value of a numeric
column.
Syntax:
SELECT AVG(column_name) FROM table_name WHERE
condition;
The following SQL query will return the average price spent by
the customers.
select AVG(Price) from customers;
16) GROUP BY CLAUSE
The GROUP BY clause is used to return data that is grouped
according to one or more columns.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s);
The below SQL statement counts the number of customers from
each city.
select count(Cust_Id), Address from customers group by
Address;
17) HAVING CLAUSE
The HAVING clause is mostly used with aggregate functions.
Having clause filters the records from groups based on specified
conditions.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
18) HAVING condition
ORDER BY column_name(s);
The following SQL query will return the cities where there are
more than 3 customers.
select count(Cust_Id), Address from customers group by
Address having count(Cust_Id)>3;
19)ORDER BY
The ORDER BY clause is used within a SELECT statement to extract
output either in ascending or descending order of columns.
Syntax:
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN] [DESC]];
The following SQL query will return the cities in an alphabetical
order.
select * from customers order by address;
JDBC (Java Database Connectivity)
• JDBC is an API in Java that enables applications to interact with
databases.
• It allows a Java program to connect to a database, execute
queries, and retrieve and manipulate data.
• By providing a standard interface, JDBC ensures that Java
applications can work with different relational databases like
MySQL, Oracle, PostgreSQL, and more.
JDBC Architecture
• Application: It is a Java applet or a servlet that communicates
with a data source.
• The JDBC API: It allows Java programs to execute SQL queries
and retrieve results. Key interfaces include Driver, ResultSet,
RowSet, PreparedStatement, and Connection. Important classes
include DriverManager, Types, Blob, and Clob.
• DriverManager: It plays an important role in the JDBC
architecture. It uses some database-specific drivers to
effectively connect enterprise applications to databases.
• JDBC drivers: These drivers handle interactions between the
application and the database.
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.
• Following is the architectural diagram, which shows the
location of the driver manager with respect to the JDBC
The JDBC architecture consists of two-tier and three-tier
processing models to access a database.
1. Two-Tier Architecture
• A Java Application communicates directly with the database
using a JDBC driver.
• Queries are sent to the database, and results are returned
directly to the application.
• In a client/server setup, the user’s machine (client)
communicates with a remote database server.
• Structure:
Client Application (Java) -> JDBC Driver -> Database
2. Three-Tier Architecture
In this, user queries are sent to a middle-tier services,
which interacts with the database.
The database results are processed by the middle tier
and then sent back to the user.
Structure:
Client Application -> Application Server -> JDBC Driver ->
Database
JDBC Components
There are generally 4 main components of JDBC through which it can
interact with a database.
1. JDBC API
It provides various methods and interfaces for easy communication with
the database.
It includes 2 key packages
a) java.sql: This package, is the part of Java Standard Edition (Java SE)
which contains the core interfaces and classes for accessing and
processing data in relational databases. It also provides essential
functionalities like establishing connections, executing queries, and
handling result sets.
b) javax.sql: This package is the part of Java Enterprise Edition (Java
EE) which extends the capabilities of java.sql by offering additional
features like connection pooling, statement pooling, and data source
management. It also provides a standard to connect a database to a client
application.
2. JDBC Driver Manager
• Driver manager is responsible for loading the correct database-specific driver to establish a connection with the
database.
• It manages the available drivers and ensures the right one is used to process user requests and interact with the
database.
3. JDBC Test Suite
It is used to test the operation(such as insertion, deletion, updating) being performed by JDBC Drivers.
4. JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert requests from Java
programs to a protocol that the DBMS can understand.
There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver (partially java driver)
3. Type-3 driver or Network Protocol driver (fully java driver)
4. Type-4 driver or Thin driver (fully java driver) – It is deprecated and no longer supported since Java 8. Instead
JDBC Classes and Interfaces
Steps to Connect to MySQL Database Using JDBC
Step 1: Load the JDBC Driver
Class.forName(“com.mysql.cj.jdbc.Driver”);
Step 2: Establish a Connection
Connection connection = DriverManager.getConnection(
“jdbc:mysql://localhost:3306/your_database”,
“your_username”,
“your_password”
);
Step 3: Create a Statement
Statement statement = connection.createStatement();
Step 4: Execute a Query
String query = “INSERT INTO students (id, name) VALUES (101, ‘John Doe’)”;
int rowsAffected = statement.executeUpdate(query);
System.out.println(“Rows affected: ” + rowsAffected);
Step 5: Close the Connection
statement.close();
connection.close();
Create a Simple JDBC Application
• The below Java program demonstrates how to establish a
MYSQL database connection using JDBC and execute a query.
// Establish connection
// Java program to implement a simple JDBC application
Connection c = DriverManager.getConnection(
import java.sql.*; url, username, password);
public class Geeks {
public static void main(String[] args) // Create a statement
{ Statement st = c.createStatement();
// Database URL, username, and password // Execute the query
// Replace with your database name int count = st.executeUpdate(query);
String url System.out.println(
"Number of rows affected by this query: "
= "jdbc:mysql://localhost:3306/your_database"; + count);
// Replace with your MySQL username
String username = "your_username"; // Close the connection
// Replace with your MySQL password st.close();
String password = "your_password"; c.close();
System.out.println("Connection closed.");
// Updated query syntax for modern databases }
String query catch (ClassNotFoundException e) {
= "INSERT INTO students (id, name) VALUES (109, System.err.println("JDBC Driver not found: "
'bhatt’)”; + e.getMessage());
// Establish JDBC Connection }
catch (SQLException e) {
try {
System.err.println("SQL Error: "
// Load Type-4 Driver + e.getMessage());
// MySQL Type-4 driver class }
Class.forName("com.mysql.cj.jdbc.Driver"); }
}
When the program runs successfully, a new record is added to the students table as
shown below.
Key Features
• Platform Independence: It enables database operations
across different platforms.
• Standard API: It provides a uniform interface for various
databases.
• Support for Multiple Databases: It works with popular
databases like MySQL, PostgreSQL, Oracle, etc.
• Extensibility: It offers features like batch processing,
connection pooling, and transaction management.
What is JDBC Driver?
• JDBC drivers implement the defined interfaces in the JDBC API, for
interacting with your database server.
• For example, using JDBC drivers enable you to open database
connections and to interact with it by sending SQL or database
commands then receiving results with Java.
• The Java.sql package that ships with JDK, contains various classes
with their behaviours defined and their actual implementations are
done in third-party drivers.
• Third party vendors implements the java.sql.Driver interface in their
database driver.
JDBC Drivers Types
• JDBC driver implementations vary because of the wide variety
of OS and hardware platforms in which Java operates.
• Sun has divided the implementation types into 4 categories,
Types 1, 2, 3, and 4.
Type 1 − JDBC-ODBC Bridge Driver
• In a Type 1 driver, a JDBC bridge is used to access ODBC drivers
installed on each client machine.
• Using ODBC, requires configuring on your system a Data Source
Name (DSN) that represents the target database.
• When Java first came out, this was a useful driver because most
databases only supported ODBC access but now this type of
driver is recommended only for experimental use or when no
other alternative is available.
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
Type 2 − JDBC-Native API
• In a Type 2 driver, JDBC API calls are converted into native C/C++
API calls, which are unique to the database.
• These drivers are typically provided by the database vendors and
used in the same manner as the JDBC-ODBC Bridge.
• The vendor-specific driver must be installed on each client machine.
• If we change the Database, we have to change the native API, as it
is specific to a database and they are mostly obsolete now, but you
may realize some speed increase with a Type 2 driver, because it
eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3 − JDBC-Net pure Java
• In a Type 3 driver, a 3-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.
• This kind of driver is extremely flexible, since it requires no code
installed on the client and a single driver can actually provide
access to multiple databases.
Type 4 − 100% Pure Java
• In a Type 4 driver, 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.
• This kind of driver is extremely flexible, you don't need to install special
software on the client or server.
• Further, these drivers can be downloaded dynamically.
MySQL's Connector/J driver is a Type 4 driver.
Because of the proprietary nature of their network protocols, database vendors usually supply
type 4 drivers.
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.