UNIT - VI: INTERACTING WITH DATABASE
Class Hours: 6 | Marks: 8
6.1 Introduction to JDBC and ODBC
ODBC (Open Database Connectivity)
- Developed by Microsoft.
- Language-independent API for accessing databases using SQL.
- Allows applications to connect to any database with an ODBC driver.
- Uses C language interfaces.
JDBC (Java Database Connectivity)
- Java API for connecting and executing queries with databases.
- Provides a standard interface for Java apps to access databases.
- JDBC is specific to Java, unlike ODBC.
6.2 JDBC Architecture
Two-Tier Architecture:
- Client <-> Database using JDBC Driver.
- Simple and good for small applications.
Three-Tier Architecture:
- Client <-> Web Server <-> Database.
- More secure, scalable, suitable for web-based applications.
6.3 Types of JDBC Drivers
1. JDBC-ODBC Bridge Driver - Legacy, uses ODBC.
2. Native-API Driver - Uses native DB libraries.
3. Network Protocol Driver - Uses middleware server.
4. Thin Driver - Pure Java, communicates directly with DB. (Best)
6.4 JDBC Classes and Interfaces
Class.forName() - Loads the JDBC driver.
DriverManager - Manages JDBC drivers and connections.
Connection - Establishes connection with DB.
Statement - Executes static SQL queries.
PreparedStatement - Executes parameterized SQL, prevents SQL injection.
ResultSet - Stores and retrieves query results.
JDBC Code Example
import java.sql.*;
class DBExample {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
"password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while(rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
con.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
Key Points for Exam
- JDBC is Java API for database access.
- DriverManager connects to DB.
- Statement and PreparedStatement are used for SQL execution.
- ResultSet reads data.
- Type 4 Driver is best for performance and portability.