Setting up JDBC (Java Database Connectivity) involves a few key steps: adding the database driver to your project, establishing a connection, and executing your SQL statements.
1. Add the JDBC Driver Dependency
First, you need the driver for your specific database (e.g., MySQL, PostgreSQL, H2) in your pom.xml.
For MySQL, you would add:
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.1.0</version>
</dependency>
2. Establish a Connection
You use the DriverManager.getConnection() method. It requires a Connection URL, username, and password.
- URL Format:
jdbc:mysql://[host]:[port]/[database_name] - Modern Java Tip: You no longer need to call
Class.forName("com.mysql.cj.jdbc.Driver")in modern JDBC (4.0+).
3. Use Try-With-Resources
Always use try-with-resources to ensure that the Connection, Statement, and ResultSet are closed automatically, preventing memory leaks.
Basic Example
Here is a concise template to get you started:
package org.kodejava.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcSetup {
private static final String URL = "jdbc:mysql://localhost:3306/your_database";
private static final String USER = "root";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
String query = "SELECT id, name FROM users";
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
} catch (SQLException e) {
System.err.println("Connection failed!");
e.printStackTrace();
}
}
}
