Reuse parameter in PreparedStatement?

I pass the parameter to PreparedStatement as follows:

public void getNodes(String runId, File file, Connection conn) { PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.prepareStatement(Mat.queries.get("NettingNode.QUERY")); ps.setString(1, runId); ps.setFetchSize(10000); rs = ps.executeQuery(); // etc. } catch (Exception e) { logger.error(e, e); } finally { close(rs, ps); } } 

And the request looks like this:

 select * from table_1 where run_id = ? 

Now I want to change my query as follows and reuse the first parameter (both ? Will use the runId parameter):

 select * from table_1 where run_id = ? union select * from table_2 where run_id = ? 

This is possible without this:

 ps.setString(1, runId); ps.setString(2, runId); 
+5
source share
1 answer

This cannot be done using simple JDBC. Instead, you can use the Spring JDBCTemplate, which will support what you want with Named Parameters, and reuse the same name wherever needed in the statement.

See Named Parameters in JDBC

+8
source

All Articles