JDBC Connection Example in Java
On this page (8sections)
Introduction
JDBC (Java Database Connectivity) is the standard API for connecting Java applications to relational databases such as MySQL, PostgreSQL and Oracle.
Prerequisites
- A running database server
- JDBC driver JAR on the classpath
- Valid URL, username and password
Example Program
import java.sql.*;
public class JdbcConnectionDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name FROM users")) {
System.out.println("Connected successfully");
System.out.println("ID\tNAME");
System.out.println("----------------");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + "\t" + name);
}
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}
Sample Output
Connected successfully
ID NAME
----------------
1 Alice
2 Bob
3 Charlie
How It Works
DriverManager.getConnection()opens a connection using the JDBC URL.createStatement()creates a SQL executor.executeQuery()runs a SELECT and returns aResultSet.- Try-with-resources closes connection, statement and result set automatically.
Best Practices
- Use
PreparedStatementwith?placeholders for dynamic values. - Never embed raw user input in SQL strings.
- Store credentials in environment variables or secure config, not source code.
Common Mistakes
- Forgetting the JDBC driver on the classpath (
ClassNotFoundException). - Not closing connections in older code — always use try-with-resources.
Frequently Asked Questions
Do I need to add a JDBC driver JAR?
Yes. Download the driver for your database (for example mysql-connector-j) and add it to the classpath, or declare it as a Maven/Gradle dependency.
Should I use Statement or PreparedStatement?
PreparedStatement is preferred for queries with user input because it prevents SQL injection and can improve performance for repeated queries.