简体   繁体   中英

reuse sql param when not using named parameters

I have a query that gets called with JdbcTemplate but only one param is getting sent and I need to use that one param in two where conditions.

The Query

String sql = "select * from employee where salary > ? and netpay > ?";

The Call

The param here is only one. IE if the id is TEST123 the query needs to be

select * from employee where id = TEST123 and name = TEST123 even though one param is getting passed.

getJdbcTemplate().query(sql, new Object[]{"TEST123"}, CustomResultSetExtractor());

Is there any way to do this from the query side instead of passing two params?

NOTE

I do not have access to change the way the query is called, hence I cannot add named params, or just pass an additional parameter.

Use NamedParameterJdbcTemplate , a JdbcTemplate wrapper:

Template class with a basic set of JDBC operations, allowing the use of named parameters rather than traditional '?' placeholders.

This class delegates to a wrapped JdbcTemplate once the substitution from named parameters to JDBC style '?' placeholders is done at execution time.

Your SQL will be with 1 parameter:

select * from employee where id = (:id) and name = (:id)

And code will be :

MapSqlParameterSource args = new MapSqlParameterSource();
args.addValue("id", TEST123);
return new NamedParameterJdbcTemplate(getJdbcTemplate()).query(sql , args, youRowMapper);

If you can't change it, you can change your query to:

 select * from employee where id = ? and id = name

I am amazed that you didn't find:

String sql = "select * from employee where id = ? and name = id";

Or did you mean or instead of and ?

String sql = "select * from employee where ? in (id, name)";

I would suggest something else, you can repeat your param in Object array for example if your query have two ? then generate the parameters like so :

String param = "TEST123";
Object[] params = IntStream.range(0, 2)
        .mapToObj(i -> param)
        .toArray();

This will generate an array which hold two time TEST123 :

[TEST123, TEST123]

Then Just send the Object array to your code like you do.

getJdbcTemplate().query(sql, params, CustomResultSetExtractor());

If you don't know the number of hold or parameters in your query you can count them like so :

int numberOfHold = sql.length() - sql.replaceAll("\\?", "").length();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM