tags:

views:

349

answers:

3

Are there named parameters in JDBC instead of positional ones, like the @name, @city in ADO.NET query below ?

select * from customers where name=@name and city = @city
+4  A: 

JDBC does not support named parameters. Unless you are bound to using plain JDBC (which causes pain, let me tell you that) I would suggest to use Springs Excellent JDBCTemplate which can be used without the whole IoC Container.

NamedParameterJDBCTemplate supports named parameters, you can use them like that:

 NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

 MapSqlParameterSource paramSource = new MapSqlParameterSource();
 paramSource.addValue("name", name);
 paramSource.addValue("city", city);
 jdbcTemplate.queryForRowSet("SELECT * FROM customers WHERE name = :name AND city = :city", paramSource);
Malax
Thanks - but I can't use springs, because I can't make that much change to existing codebase :(
Fakrudeen
the point that @Malax is making is that you can use the NamedParameterJdbcTemplate from spring standalone. You wouldn't have to change any other parts of the code base.
Gareth Davis
+1  A: 

You can't use named parameters in JDBC itself. You could try using Spring framework, as it has some extensions that allow the use of named parameters in queries.

Ivan Vrtarić
A: 

Vanilla JDBC only supports named parameters in a CallableStatement (e.g. setString("name", name)), and even then, I suspect the underlying stored procedure implementation has to support it.

skaffman