I need to select rows from mysql table based on various criteria, for example Colour= Black, or size= L.
The code works without the preparedstatement and the question marks, but whenever I attempt to use the question marks the code does not run.
I have read something about typing the question mark like ‘?’// but I am not sure about the exact format.
String URL = "jdbc:mysql://localhost:3306/clothing"; String USERNAME = "root"; String PASSWORD = "password"; Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD); Statement stmt = con.createStatement(); String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;"; ResultSet rs = stmt.executeQuery(sql); PreparedStatement preparedStmt = con.prepareStatement(sql); preparedStmt.setString(1, Data1); preparedStmt.setString(2, Data2);
Also, Size is written out in orange colour, but the error happens also when I only use this sql String
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ?;";
I have looked at like 20 different answers, but didnt find anything helpful, so thanks in advance for any help!
Advertisement
Answer
You are executing the query using a normal java.sql.Statement
, not using a java.sql.PreparedStatement
. This won’t work because a normal Statement
does not support parameterized queries. So, remove the creation and execution of the Statement
, and make sure you execute the statement using the PreparedStatement
:
String URL = "jdbc:mysql://localhost:3306/clothing"; String USERNAME = "root"; String PASSWORD = "password"; String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;"; try (Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD); PreparedStatement preparedStmt = con.prepareStatement(sql)) { preparedStmt.setString(1, Data1); preparedStmt.setString(2, Data2); try (ResultSet rs = preparedStmt.executeQuery()) { // process result set } }
Also note the addition of try-with-resources, which will ensure connections, statements and result sets are closed correctly.