JDBC (Java Database Connectivity) is a Java API that enables Java applications to interact with relational databases. It provides a standard way to execute SQL statements and retrieve data.
Key Components of JDBC
JDBC relies on several core classes and interfaces:
- Driver: Manages the connection to the database (e.g., MySQL, PostgreSQL).
- Connection: Represents a connection to a specific database.
- Statement: Executes SQL queries and updates.
- ResultSet: Stores the data returned from a database query.
- PreparedStatement: Used for precompiled SQL statements to prevent SQL injection.
Steps to Use JDBC
Add JDBC Driver
Include the appropriate JDBC driver JAR (e.g.,mysql-connector-java
) in your project.
💡 Example: For MySQL, usecom.mysql.cj.jdbc.Driver
.Load the Driver
Register the driver with theDriverManager
class.Class.forName("com.mysql.cj.jdbc.Driver");
Establish a Connection
UseDriverManager.getConnection()
to connect to the database.
🔗 Example:Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
Execute SQL Queries
Create aStatement
orPreparedStatement
to run SQL commands.
📜 Example:Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM users");
Process Results
Iterate throughResultSet
to extract data.
📌 Example:while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); }
Close Resources
Always closeResultSet
,Statement
, andConnection
to avoid leaks.
🧹 Usetry-with-resources
for automatic cleanup:try (Connection conn = ...) { // Code here }
Best Practices
✅ Use PreparedStatement
for dynamic queries.
✅ Implement connection pooling for performance.
✅ Handle exceptions properly and close resources in finally
blocks.
✅ Avoid hardcoding database credentials in production code.
Expand Your Knowledge
For a deeper dive into database connections in Java, check out our Java Database Connections Guide.