In many programming languages something like this is possible for prepared statements:
PreparedStatement statement = connection.prepareStatement( "SELECT id FROM Company WHERE name LIKE ${name}"); statement.setString("name", "IBM");
But not with java.sql.PreparedStatement. In Java one has to use parameter indices:
PreparedStatement statement = connection.prepareStatement( "SELECT id FROM Company WHERE name LIKE ?"); statement.setString(1, "IBM");
Is there a solution to work with string variables like in the first example? Is "${.*}" not used somewhere else in the SQL language, or are there any conflicts? Cause then I would implement it by myself (parsing the SQL string and replacing every variable by "?" and then doing it the Java way).
Regards, Kai
You must supply values for every parameter before executing the SQL statement. The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter.
Q 5 - Which of the following is correct about PreparedStatement? A - PreparedStatement allows mapping different requests with same prepared statement but different arguments to execute the same execution plan.
Overview of Prepared StatementsIf you want to execute a Statement object many times, it usually reduces execution time to use a PreparedStatement object instead. The main feature of a PreparedStatement object is that, unlike a Statement object, it is given a SQL statement when it is created.
Standard JDBC PreparedStatements don't have this ability. Spring JDBC provides this functionality through NamedParameterJdbcTemplate
.
As kd304 mentioned in the comment to my posting, this is a very nice solution if you don't want to incorporate another 3rd party library (like Spring) into your project: Javaworld Article: Named Parameters for PreparedStatement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With