Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable instead of a parameter index with a JDBC prepared statement

Tags:

java

jdbc

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

like image 424
Zardoz Avatar asked Jul 08 '09 12:07

Zardoz


People also ask

Which methods on the PreparedStatement can be used to bind the parameters?

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.

Which of the following statements are correct about PreparedStatement in JDBC?

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.

What is the use of PreparedStatement in JDBC?

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.


2 Answers

Standard JDBC PreparedStatements don't have this ability. Spring JDBC provides this functionality through NamedParameterJdbcTemplate.

like image 76
laz Avatar answered Sep 28 '22 18:09

laz


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

like image 37
Zardoz Avatar answered Sep 28 '22 16:09

Zardoz