JDBC (Java Database Connectivity)
Java Database Connectivity (JDBC) is an API (Application Programming Interface) that
enables Java applications to interact with relational databases. It serves as a bridge between
Java-based applications and databases like MySQL, PostgreSQL, and Oracle, allowing
seamless data retrieval, manipulation, and storage.
Key Features of JDBC:
1. Platform Independence – JDBC is part of the Java ecosystem, making it platform-
independent and allowing Java applications to connect to different databases without
modifying the code.
2. Standard API – It provides a consistent API for different relational databases, ensuring
uniform database operations.
3. SQL Execution – JDBC enables Java programs to execute SQL queries, retrieve results, and
update database records.
4. Prepared Statements – Prevents SQL injection attacks by securely handling user input in
queries.
5. Transaction Management – Allows atomic operations to maintain data consistency during
multiple transactions.
6. Connection Pooling – Improves application performance by reusing database connections
instead of creating new ones repeatedly.
JDBC Architecture:
JDBC follows a four-layered architecture:
1. JDBC API – Provides the necessary interfaces and classes to interact with databases.
2. JDBC Driver Manager – Loads the database-specific driver required to connect to the
database.
3. JDBC Drivers – Acts as a translator between Java applications and database management
systems (DBMS).
4. Database – The actual storage where data is managed and retrieved.
Steps to Use JDBC in Java:
1. Load the JDBC Driver:
[Link]("[Link]");
2. Establish a Database Connection:
Connection con = [Link]("jdbc:mysql://localhost:3306/mydb",
"user", "password");
3. Create a Statement or PreparedStatement Object:
PreparedStatement stmt = [Link]("SELECT * FROM employees WHERE id
= ?");
[Link](1, 1001);
4. Execute the Query and Process Results:
ResultSet rs = [Link]();
while ([Link]()) {
[Link]([Link]("name"));
}
5. Close the Connection:
[Link]();
Types of JDBC Drivers:
1. JDBC-ODBC Bridge Driver (Type 1) – Uses ODBC drivers but is platform-dependent.
2. Native API Driver (Type 2) – Converts JDBC calls into database-specific native calls.
3. Network Protocol Driver (Type 3) – Translates JDBC calls into middleware-server calls.
4. Thin Driver (Type 4) – Directly communicates with the database using the database’s
native protocol, making it the most efficient.
Advantages of JDBC:
- Provides an easy and consistent way to interact with databases.
- Supports both simple and complex queries, including transactions.
- Allows secure and optimized database access.
- Works with various databases by simply changing the driver configuration.
JDBC is a fundamental part of Java-based database management, ensuring secure, scalable,
and efficient data interactions for enterprise applications.