JDBC Java Data Base Connectivity
🧩 Introduction to JDBC (Java Database Connectivity)
🔷 What is JDBC?
JDBC is an API (Application Programming Interface) in Java that enables Java programs to interact with relational databases using SQL.
-
It allows developers to perform operations like:
-
Connecting to a database
-
Executing SQL queries
-
Retrieving data
-
Updating and deleting records
-
JDBC is part of the Java SE platform and is included in the java.sql
and javax.sql
packages.
📚 JDBC Overview
-
JDBC acts as a bridge between a Java application and a database.
-
It uses drivers to connect to databases like MySQL, Oracle, PostgreSQL, SQLite, etc.
-
It supports CRUD operations (Create, Read, Update, Delete).
🧱 Types of JDBC Drivers
There are four types of JDBC drivers:
Type | Name | Description |
---|---|---|
Type 1 | JDBC-ODBC Bridge Driver | Translates JDBC to ODBC API (obsolete in Java 8+) |
Type 2 | Native-API Driver | Converts JDBC calls into native database calls (requires native libraries) |
Type 3 | Network Protocol Driver | Sends JDBC calls to a middleware server that communicates with the DB |
Type 4 | Thin Driver (Pure Java) | Converts JDBC directly to database protocol (no native code, most preferred) |
✅ Steps to Develop JDBC Applications
-
Import JDBC packages
-
Register the driver
-
Establish the connection
-
Create a
Statement
orPreparedStatement
-
Execute SQL queries
-
Process the
ResultSet
-
Close the connection
🧩 Common JDBC Components
Component | Description |
---|---|
DriverManager | Manages JDBC drivers and database connections |
Connection | Interface to establish a connection to the database |
Statement | Executes SQL queries (static SQL) |
PreparedStatement | Precompiled SQL statement (dynamic and parameterized) |
ResultSet | Represents the result of a query |
SQLException | Exception class for handling database access errors |
🔌 Connection Establishment
Example: Connecting to MySQL
🧮 SQL Fundamentals with JDBC
1. Creating and Executing Basic SQL Queries
📥 Working with ResultSet
-
rs.next()
: Moves the cursor to the next row -
rs.getInt(columnName)
: Getsint
from column -
rs.getString(columnIndex)
: GetsString
by index
Example:
🛠️ Performing CRUD Operations with JDBC
🔹 CREATE (Insert)
🔹 READ (Select)
🔹 UPDATE
🔹 DELETE
✅ Best Practices
-
Use PreparedStatement instead of Statement for security (prevents SQL injection)
-
Always close resources:
ResultSet
,Statement
,Connection
-
Use try-with-resources to handle automatic closing
📦 Tools You Can Use
-
MySQL/MariaDB/PostgreSQL as RDBMS
-
XAMPP for MySQL setup
-
Eclipse/IntelliJ as IDE
-
MySQL Connector/J (JDBC driver)
Comments
Post a Comment