Java Query a Database with JDBC Parameters
JDBC is the Java database API, while a separate driver implements the connection to a particular database. Bind data values as parameters rather than concatenating them into SQL.
Understand the idea
This local lab uses the H2 2.3.232 driver and an in-memory database. It needs that driver JAR on the runtime classpath; the JDK alone does not supply an H2 driver. A PreparedStatement separates the SQL structure from a bound value. The same safety principle applies with other JDBC drivers, but SQL dialects and connection settings can differ. Keep real database credentials outside source files.
Run it locally
This JDBC example also needs the H2 2.3.232 driver JAR in your local lab folder. Download it from the official H2 distribution or resolve com.h2database:h2:2.3.232 with your build tool. The command below uses a Windows classpath separator; use : instead of ; on Linux/macOS. The database lives only in memory and is unrelated to Bhylu or your MySQL service.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp "out;h2-2.3.232.jar" MainA worked example
import java.sql.*;
public class Main {
public static void main(String[] args) throws Exception {
try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:bookings")) {
try (Statement setup = connection.createStatement()) {
setup.execute("CREATE TABLE booking (session VARCHAR(40), seats INT)");
setup.execute("INSERT INTO booking VALUES ('Clay', 4), ('Wood', 6)");
}
try (PreparedStatement query = connection.prepareStatement("SELECT seats FROM booking WHERE session = ?")) {
query.setString(1, "Wood");
try (ResultSet rows = query.executeQuery()) {
while (rows.next()) System.out.println(rows.getInt("seats"));
}
}
}
}
}
Expected output
6The parameter is supplied using setString, so it remains a value even if its characters contain SQL punctuation. Resource scopes close the result set, statement and connection in the right ownership order. The setup SQL contains only fixed fictional fixtures; application input must not be inserted into that setup style.
Check the official Java documentation and H2 setup guide for detailed contracts and supported options.