Java Database Connectivity (JDBC) - Complete Notes
1. Introduction to JDBC
Java Database Connectivity (JDBC) is a standard Java API that allows Java programs to
interact with relational databases. It provides methods for querying and updating data in a
database, making Java applications database-independent.
2. JDBC Drivers
JDBC drivers are software components that enable communication between Java
applications and databases. They handle the connection, query translation, and data
retrieval. JDBC drivers created by DBMS manufacturers perform tasks like: • Opening and
closing connections. • Translating SQL statements into DBMS-specific messages. •
Returning query results and error messages in JDBC format. • Providing transaction
management routines. Thus, JDBC drivers make Java applications
database-independent, aligning with Java’s philosophy of platform independence.
3. JDBC API Packages
The JDBC API is divided into two main packages: 1. **java.sql** (part of J2SE): Provides
core classes for connecting to databases, executing SQL queries, and handling results. 2.
**javax.sql** (part of J2EE): Extends java.sql with advanced features like connection
pooling, distributed transactions, and integration with JNDI.
4. Steps in Using JDBC
The general steps in using JDBC are: 1. Load the driver class. 2. Establish a connection
using DriverManager. 3. Create a Statement, PreparedStatement, or CallableStatement.
4. Execute queries (SELECT, INSERT, UPDATE, DELETE). 5. Process the results using
ResultSet. 6. Close the connection and resources.
5. JDBC Methods
JDBC provides several methods for executing SQL: • **executeQuery()** – Used for
SELECT statements, returns a ResultSet. • **executeUpdate()** – Used for INSERT,
UPDATE, DELETE, returns number of rows affected. • **execute()** – Can run any SQL
statement, returns boolean (true for ResultSet, false for update count). •
**executeBatch()** – Executes multiple SQL commands as a batch. • **commit()** and
**rollback()** – For transaction management.
6. JDBC Exceptions
JDBC methods can throw different types of exceptions: 1. **SQLException** – Occurs due
to SQL errors, connectivity issues, or invalid operations. - Methods: getNextException(),
getErrorCode(). 2. **SQLWarning** – Non-critical issues returned by the DBMS. -
Methods: getWarnings(), getNextWarning(). 3. **DataTruncation** – Thrown when data is
truncated during storage or retrieval.
7. Advantages of JDBC
• Platform and database independence. • Standardized API supported by most DBMS
vendors. • Supports dynamic SQL execution. • Provides strong exception handling. •
Allows connection pooling for efficient resource management.
8. Conclusion
JDBC is a vital API for Java developers, providing a seamless way to connect, query, and
interact with databases. With its standardized interface and support from almost all
commercial DBMS, JDBC continues to be the backbone of database-driven Java
applications.