JDBC (Java Database Connectivity) is a standard Java API that allows Java applications to connect to relational databases. It provides a set of interfaces and classes to send SQL queries, retrieve results and manage database connections. With JDBC, developers can build database-driven applications that are portable across various databases, including MySQL, PostgreSQL, Oracle and others.
Provides Java applications with the interface to interact with databases.
Contains classes and interfaces in the java.sql and javax.sql packages.
Example interfaces: Connection, Statement, PreparedStatement, ResultSet.
2. JDBC Driver API (Driver Layer)
Acts as a bridge between JDBC API calls and the actual database.
Converts Java method calls into database-specific calls.
2. Real-world Example of JDBC
Suppose there are two places, A (Java Application) and B (Database), where people do not understand each otherβs language. To communicate, they use a vehicle with a translator that carries messages between them.
Import JDBC package: Include java.sql classes for database operations.
Load and register driver: Load the JDBC driver class to enable communication using forname() method
Establish connection: Use DriverManager to connect to the database.
Create statement: Create Statement or PreparedStatement to send SQL queries.
Execute query: Run SQL commands like SELECT, INSERT, UPDATE or DELETE using
Process results: Retrieve and handle data from ResultSet.
Close resources: Release database connections and objects.
6. JDBC Example
Hereβs a simple example using MySQL database.
SQL Setup
Suppose we have a table students:
Java Code
7. Crud Operation with JDBC
CRUD stands for Create, Read, Update, Delete, which are the four basic operations performed on a database using JDBC.
Create: Used to insert new records into the database (INSERT query).
Read: Used to fetch records from the database (SELECT query).
Update: Used to modify existing records in the database (UPDATE query).
Delete: Used to remove records from the database (DELETE query).
8. JDBC Exception Handling
When we communicate with databases,some problems occur like:
Invalid SQL syntax bad query
Connection time out problem
Wrong data types mentioned
miss database drivers
To handle these issues gracefully, JDBC provides exception handling mechanisms
Example:
9. Transactions in JDBC
A transaction is a sequence of SQL operations that are executed as a single unit of work. Transactions help maintain data consistency and integrity in applications. By default, JDBC runs in auto-commit mode (each SQL statement is committed immediately). To manage transactions manually: