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

JDBC-SQL-Java

The document provides a comprehensive overview of JDBC (Java Database Connectivity), detailing its purpose, architecture, and key components, including JDBC drivers and their types. It covers the setup process for JDBC, how to establish connections, and the use of Statement and PreparedStatement for executing SQL queries. Additionally, it explains the ResultSet object for processing query results and emphasizes best practices for managing database connectivity and resources.

Uploaded by

anujstudent12524
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)
0 views

JDBC-SQL-Java

The document provides a comprehensive overview of JDBC (Java Database Connectivity), detailing its purpose, architecture, and key components, including JDBC drivers and their types. It covers the setup process for JDBC, how to establish connections, and the use of Statement and PreparedStatement for executing SQL queries. Additionally, it explains the ResultSet object for processing query results and emphasizes best practices for managing database connectivity and resources.

Uploaded by

anujstudent12524
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/ 12

JDBC and SQL Query Execution Study Material

Topic 1: JDBC (Java Database Connectivity)


●​ What is JDBC?
○​ JDBC is a Java API that provides a standard way to access relational
databases.
○​ It acts as a bridge between Java applications and databases.
○​ It allows Java developers to write database applications that can work with
various databases (like MySQL, Oracle, PostgreSQL, SQL Server, etc.) without
needing to write database-specific code for each one.
○​ It is part of the Java SE (Standard Edition).
●​ Purpose of JDBC:
○​ To connect to a database.
○​ To send SQL statements to the database.
○​ To process the results returned by the database.
●​ Key Features:
○​ Database Independence: Write code once, run it with different databases
(with appropriate drivers).
○​ Standard API: Provides a consistent interface for database access.
○​ Supports SQL: Allows execution of standard SQL queries.

Topic 2: JDBC Architecture


●​ The JDBC architecture consists of two layers:
1.​ JDBC API: This is the Java API used by the application developer. It consists
of a set of interfaces and classes in the java.sql and javax.sql packages.
2.​ JDBC Driver API: This API is used by driver developers to create JDBC
drivers that interact with specific database systems.
●​ Key Components in the Architecture:
○​ Application: Your Java program that uses the JDBC API.
○​ JDBC API: The set of interfaces and classes (DriverManager, Connection,
Statement, ResultSet, etc.) that your application uses.
○​ JDBC Driver Manager: A class that manages JDBC drivers. It is the first point
of contact for a Java application. It loads drivers and helps establish
connections.
○​ JDBC Driver: Database-specific software that implements the JDBC Driver
API. It translates JDBC calls into the database's native protocol and sends the
request to the database. It also translates the database's response back into
a format the JDBC API can understand.
○​ Data Source (Database): The actual database where the data is stored.
●​ Types of JDBC Drivers:
○​ Type 1: JDBC-ODBC Bridge Driver: (Legacy, not recommended for modern
applications) Translates JDBC calls into ODBC (Open Database Connectivity)
calls. Requires an ODBC driver to be installed.
○​ Type 2: Native-API Driver: Translates JDBC calls into native database API
calls. Requires native database client libraries to be installed on the client
machine.
○​ Type 3: Network Protocol Driver (Middleware Driver): Uses a middleware
server that translates JDBC calls into a database-specific network protocol.
The Java client communicates with the middleware server using a standard
network protocol.
○​ Type 4: Native-Protocol Pure Java Driver: Communicates directly with the
database using the database's native protocol, written entirely in Java. This is
the most common and preferred type of driver today.

Topic 3: JDBC Environment Setup


●​ Prerequisites:
○​ Java Development Kit (JDK): You need Java installed to write and run JDBC
applications.
○​ Database: You need a database system installed or accessible (e.g., MySQL,
PostgreSQL, Oracle, SQL Server).
○​ JDBC Driver: You need the specific JDBC driver for the database you are
using. This is usually a JAR file provided by the database vendor.
●​ Steps for Setup:
1.​ Install JDK: Download and install the latest JDK from Oracle or OpenJDK.
2.​ Install/Access Database: Set up your database and ensure it's running and
accessible.
3.​ Download JDBC Driver: Download the JDBC driver JAR file for your specific
database version. For example:
■​ MySQL Connector/J for MySQL
■​ PostgreSQL JDBC Driver for PostgreSQL
■​ Oracle JDBC Driver (ojdbc) for Oracle
4.​ Add JDBC Driver to Project's Classpath: This is crucial so your Java
program can find and load the driver classes.
■​ In an IDE (like Eclipse, IntelliJ IDEA, NetBeans): Usually involves adding
the JAR file to the project's build path or module path.
■​ From Command Line: Include the JAR file in the -classpath or -cp
argument when compiling and running your Java code.

Topic 4: JDBC Drivers


●​ Role of a JDBC Driver:
○​ Implements the java.sql.Driver interface.
○​ Responsible for establishing a connection to a specific database.
○​ Translates standard JDBC calls into the database's native communication
protocol.
○​ Handles the communication with the database.
●​ Loading a JDBC Driver:
○​ Historically, drivers were explicitly loaded using
Class.forName("com.mysql.cj.jdbc.Driver"); (example for MySQL). This is often
referred to as explicitly registering the driver.
○​ Since JDBC 4.0 (Java SE 6), the DriverManager can automatically load drivers
if they are in the classpath and include a specific file
(META-INF/services/java.sql.Driver) in their JAR. Explicitly loading with
Class.forName() is often no longer necessary but is still commonly seen and
works.
○​ The recommended way in modern Java is often to let the DriverManager
automatically load the driver.

Topic 5: Connection
●​ What is a Connection?
○​ An object that represents a physical connection to a database.
○​ It is the primary means of communication with the database.
○​ All database operations (executing queries, managing transactions) are
performed through a Connection object.
●​ Establishing a Connection:
○​ The DriverManager.getConnection() method is used to establish a connection.
○​ It takes a database URL, username, and password as arguments.
○​ Database URL Format: jdbc:subprotocol:subname
■​ jdbc: The protocol.
■​ subprotocol: The name of the JDBC driver being used (e.g., mysql,
postgresql, oracle).
■​ subname: Varies depending on the driver and database, usually includes
host, port, and database name (e.g., //localhost:3306/mydatabase).
●​ Example Code (Establishing a Connection):

import java.sql.Connection;​
import java.sql.DriverManager;​
import java.sql.SQLException;​

public class DatabaseConnection {​
public static void main(String[] args) {​
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Replace with your DB
details​
String user = "myuser"; // Replace with your DB username​
String password = "mypassword"; // Replace with your DB password​

try (Connection connection = DriverManager.getConnection(url, user, password))
{​
// Connection is successfully established here​
System.out.println("Database connection successful!");​
// You can now use the 'connection' object to perform database operations​
} catch (SQLException e) {​
System.err.println("Database connection failed!");​
e.printStackTrace();​
}​
}​
}​

●​ Closing a Connection:
○​ It is crucial to close the connection when you are finished with it to release
resources.
○​ Use the close() method of the Connection object.
○​ Using a try-with-resources block (as shown in the example above) is the
recommended way to ensure the connection is closed automatically, even if
errors occur.

Topic 6: Statement
●​ What is a Statement?
○​ An object used to execute static SQL statements and return results.
○​ Suitable for executing SQL queries where the SQL string is fixed and does not
change with different data.
●​ Creating a Statement:
○​ Obtained from a Connection object using the createStatement() method:​
Statement statement = connection.createStatement();​
●​ Executing SQL Queries with Statement:
○​ executeQuery(String sql): For executing SELECT queries. Returns a ResultSet.
○​ executeUpdate(String sql): For executing INSERT, UPDATE, DELETE, and DDL
(Data Definition Language) statements (like CREATE TABLE, DROP TABLE).
Returns an integer representing the number of rows affected for DML
statements.
○​ execute(String sql): For executing SQL statements that might return multiple
results or different types of results. Useful for stored procedures. Returns true
if the first result is a ResultSet, false if it's an update count or no result.
●​ Example Code (Using Statement for SELECT):

// Assuming 'connection' is an established Connection object​



try (Statement statement = connection.createStatement()) {​
String sql = "SELECT id, name, age FROM users";​
try (ResultSet resultSet = statement.executeQuery(sql)) {​
// Process the results using the ResultSet (see Topic 8)​
}​
} catch (SQLException e) {​
e.printStackTrace();​
}​

●​ Example Code (Using Statement for INSERT/UPDATE/DELETE):

// Assuming 'connection' is an established Connection object​



try (Statement statement = connection.createStatement()) {​
String sql = "INSERT INTO products (name, price) VALUES ('Laptop', 1200.00)";​
int rowsAffected = statement.executeUpdate(sql);​
System.out.println(rowsAffected + " row(s) inserted.");​
} catch (SQLException e) {​
e.printStackTrace();​
}​

●​ Limitations of Statement:
○​ Vulnerable to SQL injection if user input is directly concatenated into the SQL
string.
○​ Performance can be lower for repeated executions of the same query with
different data, as the database has to parse and plan the query each time.

Topic 7: Prepared Statement


●​ What is a Prepared Statement?
○​ An object used to execute precompiled SQL statements with input
parameters.
○​ Extends Statement.
○​ The SQL statement is sent to the database and precompiled before the actual
values are provided.
●​ Why use Prepared Statement?
○​ Security: Prevents SQL injection. Parameter values are sent separately from
the SQL command, preventing malicious code from being injected.
○​ Performance: The database precompiles the statement, leading to better
performance for repeated executions of the same query with different
parameter values.
○​ Readability and Maintainability: Makes code cleaner by separating the SQL
logic from the data.
●​ Creating a Prepared Statement:
○​ Obtained from a Connection object using the prepareStatement(String sql)
method. The SQL string contains question marks (?) as placeholders for
parameters.​
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";​
PreparedStatement preparedStatement = connection.prepareStatement(sql);​

●​ Setting Parameters:
○​ Use the setX(int parameterIndex, X value) methods, where X is the data type
(e.g., setString, setInt, setDouble). The parameterIndex starts from 1.​
preparedStatement.setString(1, "Alice");​
preparedStatement.setInt(2, 30);​

●​ Executing Queries with Prepared Statement:


○​ executeQuery(): For SELECT statements. Returns a ResultSet.
○​ executeUpdate(): For INSERT, UPDATE, DELETE, and DDL statements. Returns
the number of rows affected.
○​ execute(): Similar to Statement.execute().
●​ Example Code (Using Prepared Statement for INSERT):

// Assuming 'connection' is an established Connection object​



String sql = "INSERT INTO products (name, price) VALUES (?, ?)";​
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {​
preparedStatement.setString(1, "Keyboard");​
preparedStatement.setDouble(2, 75.00);​
int rowsAffected = preparedStatement.executeUpdate();​
System.out.println(rowsAffected + " row(s) inserted.");​

// Execute again with different values​
preparedStatement.setString(1, "Mouse");​
preparedStatement.setDouble(2, 25.50);​
rowsAffected = preparedStatement.executeUpdate();​
System.out.println(rowsAffected + " row(s) inserted.");​

} catch (SQLException e) {​
e.printStackTrace();​
}​

●​ Example Code (Using Prepared Statement for SELECT):

// Assuming 'connection' is an established Connection object​



String sql = "SELECT id, name, age FROM users WHERE age > ?";​
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {​
preparedStatement.setInt(1, 25);​
try (ResultSet resultSet = preparedStatement.executeQuery()) {​
// Process the results using the ResultSet (see Topic 8)​
}​
} catch (SQLException e) {​
e.printStackTrace();​
}​

Topic 8: ResultSet
●​ What is a ResultSet?
○​ An object that represents the data returned by a database query, typically a
SELECT statement.
○​ It acts as an iterator, providing methods to move through the rows of the
query result.
○​ It holds a cursor that points to the current row. Initially, the cursor is
positioned before the first row.
●​ Processing a ResultSet:
○​ next(): Moves the cursor to the next row. Returns true if there is a next row,
false otherwise. You typically use this in a while loop to iterate through all
rows.
○​ getX(int columnIndex) or getX(String columnLabel): Retrieves the value of the
specified column in the current row, where X is the data type (e.g., getString,
getInt, getDouble, getDate). Column indexes start from 1. Using column labels
(names) is generally preferred for readability.
●​ Example Code (Processing a ResultSet):

// Assuming 'resultSet' is a ResultSet object obtained from a query​



try {​
while (resultSet.next()) {​
// Get data from the current row​
int id = resultSet.getInt("id"); // or resultSet.getInt(1);​
String name = resultSet.getString("name"); // or resultSet.getString(2);​
int age = resultSet.getInt("age"); // or resultSet.getInt(3);​

// Do something with the retrieved data​
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);​
}​
} catch (SQLException e) {​
e.printStackTrace();​
} finally {​
// In a try-with-resources block for the Statement/PreparedStatement and
ResultSet,​
// explicit closing is not needed as resources are automatically closed.​
// If not using try-with-resources, you would close here:​
// if (resultSet != null) try { resultSet.close(); } catch (SQLException e) {
e.printStackTrace(); }​
}​

●​ Closing a ResultSet:
○​ Like Connection and Statement, ResultSet objects should be closed to release
resources.
○​ Using a try-with-resources block is the best practice.

Topic 9: Connectivity to Database using JDBC


●​ This topic consolidates the steps discussed earlier:
1.​ Ensure Prerequisites: Have JDK, database, and JDBC driver ready.
2.​ Add Driver to Classpath: Make the JDBC driver JAR accessible to your Java
program.
3.​ Load the Driver: (Optional for modern JDBC drivers, but common practice)
Class.forName("your.jdbc.driver.ClassName");
4.​ Establish a Connection: Use DriverManager.getConnection(url, user,
password) to get a Connection object.
5.​ Handle Exceptions: Always use try-catch blocks to handle SQLException,
which is thrown by most JDBC operations.
6.​ Close Resources: Use try-with-resources to ensure Connection, Statement,
PreparedStatement, and ResultSet objects are closed properly.
●​ Example of Full Connectivity Flow:

import java.sql.Connection;​
import java.sql.DriverManager;​
import java.sql.SQLException;​
import java.sql.Statement;​
import java.sql.ResultSet;​

public class JDBCExample {​
// Database credentials and URL​
static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";​
static final String USER = "myuser";​
static final String PASS = "mypassword";​

public static void main(String[] args) {​
// Using try-with-resources for automatic resource management​
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);​
Statement stmt = conn.createStatement();​
ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM users")) {​

// Process the results​
while (rs.next()) {​
int id = rs.getInt("id");​
String name = rs.getString("name");​
int age = rs.getInt("age");​
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);​
}​

} catch (SQLException e) {​
e.printStackTrace();​
}​
}​
}​

Topic 10: SQL Query Execution (Create, Insert, Update, Delete


and Retrieve) using JDBC
This topic combines the SQL operations with the JDBC Statement and
PreparedStatement objects.
●​ Assumed Database Table (Example): Let's assume a table named products
with columns id (INT, primary key, auto-increment), name (VARCHAR), and price
(DOUBLE).
●​ 1. Create (Table): (DDL operation - typically done once)
○​ Use Statement.executeUpdate() or PreparedStatement.executeUpdate().
○​ SQL: CREATE TABLE products (id INT AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(255), price DOUBLE)
○​ JDBC Code (using Statement):

try (Statement stmt = connection.createStatement()) {​


String sql = "CREATE TABLE products (id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255), price DOUBLE)";​
stmt.executeUpdate(sql);​
System.out.println("Table 'products' created successfully.");​
} catch (SQLException e) {​
e.printStackTrace();​
}​

●​ 2. Insert (Data): (DML operation)


○​ Use Statement.executeUpdate() or PreparedStatement.executeUpdate().
PreparedStatement is highly recommended for inserting data to prevent SQL
injection.
○​ SQL (using placeholders): INSERT INTO products (name, price) VALUES (?,
?)
○​ JDBC Code (using PreparedStatement):

String sql = "INSERT INTO products (name, price) VALUES (?, ?)";​
try (PreparedStatement preparedStatement = connection.prepareStatement(sql))
{​
preparedStatement.setString(1, "Tablet");​
preparedStatement.setDouble(2, 350.00);​
int rowsAffected = preparedStatement.executeUpdate();​
System.out.println(rowsAffected + " row(s) inserted.");​
} catch (SQLException e) {​
e.printStackTrace();​
}​

●​ 3. Retrieve (Data): (DML operation)


○​ Use Statement.executeQuery() or PreparedStatement.executeQuery(). Use
PreparedStatement if you have search criteria based on variables.
○​ SQL: SELECT id, name, price FROM products (Retrieve all)
○​ SQL (with WHERE clause): SELECT id, name, price FROM products WHERE
price > ?
○​ JDBC Code (using Statement for all):

try (Statement stmt = connection.createStatement();​


ResultSet rs = stmt.executeQuery("SELECT id, name, price FROM
products")) {​
while (rs.next()) {​
int id = rs.getInt("id");​
String name = rs.getString("name");​
double price = rs.getDouble("price");​
System.out.println("ID: " + id + ", Name: " + name + ", Price: " + price);​
}​
} catch (SQLException e) {​
e.printStackTrace();​
}​

○​ JDBC Code (using PreparedStatement with WHERE):

String sql = "SELECT id, name, price FROM products WHERE price > ?";​
try (PreparedStatement preparedStatement = connection.prepareStatement(sql))
{​
preparedStatement.setDouble(1, 100.00);​
try (ResultSet rs = preparedStatement.executeQuery()) {​
while (rs.next()) {​
int id = rs.getInt("id");​
String name = rs.getString("name");​
double price = rs.getDouble("price");​
System.out.println("ID: " + id + ", Name: " + name + ", Price: " + price);​
}​
}​
} catch (SQLException e) {​
e.printStackTrace();​
}​

●​ 4. Update (Data): (DML operation)


○​ Use Statement.executeUpdate() or PreparedStatement.executeUpdate().
PreparedStatement is highly recommended.
○​ SQL (using placeholders): UPDATE products SET price = ? WHERE name = ?
○​ JDBC Code (using PreparedStatement):

String sql = "UPDATE products SET price = ? WHERE name = ?";​


try (PreparedStatement preparedStatement = connection.prepareStatement(sql))
{​
preparedStatement.setDouble(1, 150.00); // New price​
preparedStatement.setString(2, "Keyboard"); // Product name​
int rowsAffected = preparedStatement.executeUpdate();​
System.out.println(rowsAffected + " row(s) updated.");​
} catch (SQLException e) {​
e.printStackTrace();​
}​

●​ 5. Delete (Data): (DML operation)


○​ Use Statement.executeUpdate() or PreparedStatement.executeUpdate().
PreparedStatement is highly recommended.
○​ SQL (using placeholders): DELETE FROM products WHERE name = ?
○​ JDBC Code (using PreparedStatement):

String sql = "DELETE FROM products WHERE name = ?";​


try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {​
preparedStatement.setString(1, "Mouse"); // Product name to delete​
int rowsAffected = preparedStatement.executeUpdate();​
System.out.println(rowsAffected + " row(s) deleted.");​
} catch (SQLException e) {​
e.printStackTrace();​
}​

You might also like