PreparedStatement statement = connection.prepareStatement("SELECT name, address FROM customers WHERE age > ?"); statement.setInt(1, 18); ResultSet result = statement.executeQuery(); while (result.next()) { String name = result.getString("name"); String address = result.getString("address"); System.out.println(name + " - " + address); } result.close(); statement.close();
PreparedStatement statement = connection.prepareStatement("SELECT c.name, o.price FROM customers c INNER JOIN orders o ON c.id = o.customer_id WHERE c.country = ?"); statement.setString(1, "USA"); ResultSet result = statement.executeQuery(); while (result.next()) { String name = result.getString("name"); double price = result.getDouble("price"); System.out.println(name + " - " + price); } result.close(); statement.close();In the above code example, we create a PreparedStatement object with a SELECT statement that retrieves the names and prices of orders made by customers from the USA. We set the value of the country parameter using the setString() method. We then use the executeQuery() method to execute the statement and retrieve the result set. We iterate over the result set and print out the name and price of each order. Finally, we close the result set and statement objects. Package/library: java.sql.