JDBC (Java Database Connectivity) is the standard API for connecting a Java application to a relational database like MySQL or PostgreSQL - it is the same idea behind this very site's PHP/MySQL backend, just from the Java side.
The basic pattern
String url = "jdbc:mysql://localhost:3306/school";
String user = "root";
String password = "yourpassword";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
String sql = "SELECT name, age FROM students WHERE age > ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, 18);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("name") + " - " + rs.getInt("age"));
}
}
}
} catch (SQLException e) {
System.out.println("Database error: " + e.getMessage());
}
Always use PreparedStatement, never string concatenation
Building SQL by concatenating strings with user input opens the door to SQL injection - the same vulnerability class this site's own PHP code is careful to avoid with parameterized queries:
// DANGEROUS - never do this:
String sql = "SELECT * FROM students WHERE name = '" + userInput + "'";
// SAFE - the ? is filled in separately, never interpreted as SQL:
String sql = "SELECT * FROM students WHERE name = ?";
stmt.setString(1, userInput);
Connection, Statement, ResultSet - the three core pieces
Connection represents the link to the database. PreparedStatement represents one parameterized SQL command. ResultSet is the cursor you step through to read query results row by row with rs.next(). All three implement Closeable, which is why they are all opened inside try-with-resources.