Java
JDBC
Database connection and operations.
By EZ4Code Team
jdbcdatabase
Code
import java.sql.*;
// Connect to database
try (Connection conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/mydb", "user", "pass")) {
// Query
try (PreparedStatement stmt = conn.prepareStatement(
"SELECT id, name FROM users WHERE age > ?")) {
stmt.setInt(1, 18);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + ": " + name);
}
}
}
// Transaction
conn.setAutoCommit(false);
try (PreparedStatement stmt = conn.prepareStatement(
"UPDATE accounts SET balance = balance - ? WHERE id = ?")) {
stmt.setInt(1, 100);
stmt.setInt(2, 1);
stmt.executeUpdate();
conn.commit();
} catch (SQLException e) {
conn.rollback();
}
}Explanation
JDBC is the standard API for Java database access; PreparedStatement prevents SQL injection.
More Java Snippets
String Operations and StringBuilder
Manipulate strings with split, join, substring, and StringBuilder in Java.
Stream API
Process collections using the Stream API.
Lambda Expressions
Simplify code with Lambda expressions.
Optional
Handle null values elegantly.
Collection Operations
Common operations on List, Set, and Map.
Exception Handling
try-catch-finally and custom exceptions.