Repository navigation
JDBC
Zhamri Che Ani edited this page May 18, 2026
·
1 revision
JDBC stands for Java Database Connectivity.
It is a Java API used to:
- connect Java applications to databases,
- execute SQL queries,
- retrieve data,
- update/delete/insert records.
JDBC allows Java programs to communicate with databases such as:
- MySQL
- Oracle
- PostgreSQL
- Microsoft SQL Server
Flow:
Java Application
↓
JDBC API
↓
JDBC Driver
↓
Database
The JDBC Driver acts like a translator between Java and the database.
A JDBC driver is required to connect Java to a database.
Example:
For MySQL:
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.0.0</version>
</dependency>| Component | Purpose |
|---|---|
DriverManager |
Creates database connection |
Connection |
Represents database connection |
Statement |
Executes SQL |
PreparedStatement |
Executes parameterized SQL |
ResultSet |
Stores query result |
SQLException |
Handles database errors |
import java.sql.*;Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb",
"root",
"password"
);Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery(
"SELECT * FROM students"
);int rows = stmt.executeUpdate(
"INSERT INTO students VALUES (1,'Ali')"
);while(rs.next()) {
System.out.println(rs.getInt("id"));
System.out.println(rs.getString("name"));
}rs.close();
stmt.close();
conn.close();Statement stmt = conn.createStatement();Problem:
- vulnerable to SQL Injection
- slower for repeated queries
PreparedStatement ps =
conn.prepareStatement(
"SELECT * FROM students WHERE id=?"
);
ps.setInt(1, 1);
ResultSet rs = ps.executeQuery();Advantages:
- More secure
- Faster
- Prevents SQL Injection
- Easier parameter handling
Used when multiple SQL operations must succeed together.
conn.setAutoCommit(false);
conn.commit();
conn.rollback();Example:
- banking system
- payment transfer
- inventory system
Useful for large data insertion.
ps.addBatch();
ps.executeBatch();Good for:
- importing Excel data
- bulk insert
- processing thousands of records
Common in:
- Servlet/JSP
- Java EE
- Spring Boot
Architecture:
Servlet → DAO → JDBC → Database
jdbc:mysql://localhost:3306/dbname
jdbc:postgresql://localhost:5432/dbname
jdbc:oracle:thin:@localhost:1521/XEPDB1
jdbc:sqlserver://localhost:1433;databaseName=testdb