Careeroza
Connecting and Querying
Connection URL
| Database | URL |
|---|---|
| MySQL | jdbc:mysql://localhost:3306/shopease |
| PostgreSQL | jdbc:postgresql://localhost:5432/shopease |
| H2 in-memory (tests) | jdbc:h2:mem:testdb |
Reading Rows
import java.sql.*;
public class ProductQuery {
private static final String URL = "jdbc:mysql://localhost:3306/shopease";
public static void main(String[] args) {
String sql = "SELECT id, name, price, stock FROM product WHERE category = ? ORDER BY price";
// try-with-resources closes ResultSet, Statement and Connection in reverse order
try (Connection con = DriverManager.getConnection(URL, System.getenv("DB_USER"), System.getenv("DB_PASS"));
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, "Electronics");
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.printf("%d %-12s %10.2f %4d%n",
rs.getLong("id"), rs.getString("name"),
rs.getBigDecimal("price"), rs.getInt("stock"));
}
}
} catch (SQLException e) {
System.err.println("DB error " + e.getSQLState() + ": " + e.getMessage());
}
}
}Output
Sample run against the ShopEase database (rows ordered by price):
java -cp .:mysql-connector-j-8.4.0.jar ProductQueryExample output
7 Cable 199.00 140 2 Charger 899.00 60 3 Earbuds 1999.00 25 1 Phone 15999.00 12
Writing Rows
String insert = "INSERT INTO product (name, price, stock, category) VALUES (?, ?, ?, ?)";
try (Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, "Smart Watch");
ps.setBigDecimal(2, new BigDecimal("4999.00"));
ps.setInt(3, 40);
ps.setString(4, "Electronics");
int rows = ps.executeUpdate(); // INSERT / UPDATE / DELETE
try (ResultSet keys = ps.getGeneratedKeys()) {
if (keys.next()) System.out.println(rows + " row inserted, id = " + keys.getLong(1));
}
}| Method | Use for | Returns |
|---|---|---|
executeQuery() | SELECT | ResultSet |
executeUpdate() | INSERT, UPDATE, DELETE, DDL | rows affected (int) |
execute() | unknown SQL | true if a ResultSet is available |
executeBatch() | many statements at once | int[] of counts |