Module 5: JDBC
1. JDBC Architecture and Types of JDBC Drivers:
JDBC Architecture:
- Java application uses JDBC API to interact with the database.
- JDBC Drivers act as an interface between the application and the database.
Diagram:
Java Application -> JDBC API -> JDBC Driver -> Database
Types of JDBC Drivers:
Type 1 - JDBC-ODBC Bridge Driver: Uses ODBC driver; slow and outdated.
Type 2 - Native-API Driver: Converts JDBC to native DB calls.
Type 3 - Network Protocol Driver: Sends JDBC calls over the network to middleware.
Type 4 - Thin Driver: Direct JDBC to database protocol (fastest).
2. JDBC Program for Student Database (CRUD):
import java.sql.*;
public class StudentCRUD {
public static void main(String[] args) throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO students VALUES (1, 'John')");
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
stmt.executeUpdate("UPDATE students SET name='Johnny' WHERE id=1");
stmt.executeUpdate("DELETE FROM students WHERE id=1");
con.close();
3. Transaction Management:
Connection con = DriverManager.getConnection(...);
try {
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO accounts VALUES(1, 5000)");
stmt.executeUpdate("UPDATE accounts SET balance = balance - 1000 WHERE id = 1");
con.commit();
} catch (SQLException e) {
con.rollback();
e.printStackTrace();
4. Statement vs PreparedStatement vs CallableStatement:
Statement: General SQL, not safe from SQL injection.
PreparedStatement: Precompiled, safe from SQL injection.
CallableStatement: Used for stored procedures.
Example:
Statement stmt = con.createStatement();
PreparedStatement ps = con.prepareStatement("INSERT INTO students VALUES (?, ?)");
CallableStatement cs = con.prepareCall("{call myProc(?, ?)}");
5. Metadata (DatabaseMetaData & ResultSetMetaData):
DatabaseMetaData dbmd = con.getMetaData();
System.out.println("DB Name: " + dbmd.getDatabaseProductName());
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("Columns: " + rsmd.getColumnCount());
6. SQLException Handling:
try {
Connection con = DriverManager.getConnection(...);
Statement stmt = con.createStatement();
stmt.executeUpdate("WRONG SQL");
} catch (SQLException e) {
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Message: " + e.getMessage());
System.out.println("SQL State: " + e.getSQLState());
} finally {
if (con != null) con.close();