Module-3 JDBC Concepts
Module-3 JDBC Concepts
JDBC (Java Database Connectivity) is a Java API that allows Java applications to connect to
and interact with relational databases (like MySQL, Oracle, PostgreSQL). It provides
methods to execute SQL queries, retrieve data, and manage database transactions.
Driver: Software component that handles the communication with the database.
Connection: Establishes a connection between the Java application and the database.
Statement: Used to execute SQL queries.
ResultSet: Stores the results of SQL queries.
SQLException: Handles database-related exceptions.
3. JDBC Architecture
java
Copy code
Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish a Connection:
java
Copy code
3. Create a Statement:
java
Copy code
Statement stmt = conn.createStatement();
4. Execute a Query:
java
Copy code
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
java
Copy code
while (rs.next()) {
System.out.println(rs.getString("username"));
}
java
Copy code
conn.close();
6. JDBC Interfaces
7. Types of Statements
1. Statement:
o Executes static SQL queries.
java
Copy code
Statement stmt = conn.createStatement();
stmt.executeQuery("SELECT * FROM users");
2. PreparedStatement:
o Executes parameterized queries, which improves security and performance.
java
Copy code
3. CallableStatement:
o Used to call stored procedures from a database.
java
Copy code
CallableStatement cstmt = conn.prepareCall("{call getUserById(?)}");
cstmt.setInt(1, 5);
ResultSet rs = cstmt.executeQuery();
8. ResultSet Object
Example of a transaction:
java
Copy code
conn.setAutoCommit(false); // Disable auto-commit
try {
stmt.executeUpdate("INSERT INTO users VALUES (1, 'John')");
stmt.executeUpdate("INSERT INTO accounts VALUES (1, 1000)");
conn.commit(); // Commit the transaction
} catch (SQLException e) {
conn.rollback(); // Roll back on error
}
java
Copy code
try {
Connection conn = DriverManager.getConnection(...);
} catch (SQLException e) {
e.printStackTrace();
How it works: Converts JDBC calls into ODBC (Open Database Connectivity)
calls, allowing Java to interact with databases through ODBC drivers.
Architecture:
Java Application → JDBC API → ODBC Driver → Database
Advantages:
Disadvantages:
How it works: Converts JDBC calls into database-specific native library calls.
Architecture:
Java Application → JDBC API → Native Library (DB-specific) → Database
Advantages:
Disadvantages:
How it works: Uses a middleware server that translates JDBC calls into database-
specific protocol.
Architecture:
Java Application → JDBC API → Middleware Server → Database
Advantages:
Disadvantages:
How it works: Converts JDBC calls directly into the database’s native protocol.
Architecture:
Java Application → JDBC API → Database
Advantages:
Disadvantages:
java.sql
javax.sql
These packages contain essential interfaces and classes that help establish connections,
execute SQL statements, manage transactions, and retrieve query results.
1. java.sql Package
The java.sql package provides the core functionality for interacting with relational
databases.
1. DriverManager
o Manages JDBC drivers and establishes connections.
java
Copy code
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "user", "password");
2. Connection
o Represents a connection to the database.
o Methods:
createStatement(): Creates a Statement object.
prepareStatement(): Creates a PreparedStatement.
setAutoCommit(): Enables/disables auto-commit mode.
close(): Closes the connection.
3. Statement
o Used to execute static SQL queries.
java
Copy code
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
4. PreparedStatement
o Used for parameterized SQL queries to improve performance and prevent SQL
injection.
java
Copy code
PreparedStatement pstmt = conn.prepareStatement(
"SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 101);
ResultSet rs = pstmt.executeQuery();
5. CallableStatement
o Used to call stored procedures from the database.
java
Copy code
CallableStatement cstmt = conn.prepareCall("{call getUserById(?)}");
cstmt.setInt(1, 5);
ResultSet rs = cstmt.executeQuery();
6. ResultSet
o Stores results of SQL queries.
o Methods:
next(): Moves the cursor to the next row.
getString(), getInt(): Retrieve column values by name or index.
7. SQLException
o Handles exceptions that occur during database operations.
java
Copy code
try {
Connection conn = DriverManager.getConnection(...);
} catch (SQLException e) {
e.printStackTrace();
}
2. javax.sql Package
1. DataSource
o An alternative to DriverManager for establishing connections, often used with
connection pools.
java
Copy code
DataSource ds = new MysqlDataSource();
Connection conn = ds.getConnection();
2. ConnectionPoolDataSource
o Provides connections from a connection pool, improving performance in high-
demand environments.
3. PooledConnection
java.sql Core JDBC functionality like connections and queries Basic database operations
Use java.sql for standard database operations like queries and updates.
Use javax.sql when working with enterprise-level applications, connection pooling, or
distributed systems.
These packages provide all the tools needed to interact with databases efficiently and handle
different application requirements—from simple queries to high-performance enterprise
solutions.
This step ensures that the appropriate JDBC driver is loaded into memory.
Example:
java
Copy code
Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish a Connection
java
Copy code
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "user", "password");
The getConnection() method returns a Connection object used to interact with the
database.
java
Copy code
Statement stmt = conn.createStatement();
java
Copy code
PreparedStatement pstmt = conn.prepareStatement(
"SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 101);
java
Copy code
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
java
Copy code
int rowsAffected = stmt.executeUpdate(
"INSERT INTO users (id, name) VALUES (101, 'Alice')");
java
Copy code
while (rs.next()) {
System.out.println("User ID: " + rs.getInt("id"));
System.out.println("User Name: " + rs.getString("name"));
}
java
Copy code
try {
Connection conn = DriverManager.getConnection(...);
} catch (SQLException e) {
e.printStackTrace();
}
java
Copy code
rs.close();
stmt.close();
conn.close();
Summary
The JDBC process enables Java applications to interact with databases by following these
steps:
A connection represents the session between a Java application and the database.
Establishing a connection is the first step in interacting with the database.
java
Copy code
Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish a Connection:
java
Copy code
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "username", "password");
xml
Copy code
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.x</version>
</dependency>
Statement Objects
java
Copy code
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
java
Copy code
PreparedStatement pstmt = conn.prepareStatement(
"SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 101);
ResultSet rs = pstmt.executeQuery();
java
Copy code
CallableStatement cstmt = conn.prepareCall("{call getUserById(?)}");
cstmt.setInt(1, 5);
ResultSet rs = cstmt.executeQuery();
ResultSet
The ResultSet object holds the result of a SELECT query and provides methods to access
and manipulate the data.
Example:
java
Copy code
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id"));
System.out.println("Name: " + rs.getString("name"));
}
Transaction Processing
java
Copy code
conn.setAutoCommit(false);
2. Execute Queries:
java
Copy code
stmt.executeUpdate("INSERT INTO accounts VALUES (1, 'Alice', 5000)");
stmt.executeUpdate("INSERT INTO transactions VALUES (1, 'Deposit',
5000)");
java
Copy code
conn.commit();
java
Copy code
conn.rollback();
Metadata
Metadata provides information about the database and the result set.
Database Metadata:
java
Copy code
DatabaseMetaData dbMeta = conn.getMetaData();
System.out.println("Database Product Name: " +
dbMeta.getDatabaseProductName());
ResultSet Metadata:
java
Copy code
ResultSetMetaData rsMeta = rs.getMetaData();
int columnCount = rsMeta.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
Data Types
MySQL supports various data types for storing information. Here are the most common
types:
sql
Copy code
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Exception Handling
Exceptions can occur during database operations, such as connection issues, SQL syntax
errors, or query failures. JDBC uses the SQLException class to handle these exceptions.
These concepts are essential for building Java applications that interact with MySQL
databases efficiently and reliably.
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
Connection connection;
jdbcdriver = "com.mysql.jdbc.Driver";
dbURL = "jdbc:mysql://localhost:3306/dbexample";
username = "root";
password = "root";
Class.forName(jdbcdriver);
connection = DriverManager.getConnection(dbURL,username,password);
PreparedStatement st = connection.prepareStatement(query);
return st.executeQuery();
PreparedStatement st = connection.prepareStatement(statement);
return st.executeUpdate();
try {
connection.close();