JDBC Connection Example in Java
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 CharlieBest Practices
Common Mistakes
How It Works
Here is a step-by-step walkthrough of how the Java program for JDBC Connection Example in Java runs, line by line:
public class JdbcConnectionDemo {— performs part of the program’s logic.public static void main(String[] args) {— defines a function used by the program.String url = "jdbc:mysql://localhost:3306/testdb";— declares or assigns a value the program uses.String user = "root";— declares or assigns a value the program uses.String password = "password";— declares or assigns a value the program uses.try (Connection conn = DriverManager.getConnection(url, user, password);— declares or assigns a value the program uses.Statement stmt = conn.createStatement();— declares or assigns a value the program uses.ResultSet rs = stmt.executeQuery("SELECT id, name FROM users")) {— declares or assigns a value the program uses.
After running it, compare your console output with the Sample Output above. Try changing the values and re-running the program to see how the result changes — experimenting is the fastest way to understand the logic.
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.