I am passing a parameter to a PreparedStatement like this :
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 query looks like this :
select * from table_1 where run_id = ?
Now I want to modify my query like this, and reuse the first parameter (both ?
would use the runId parameter) :
select * from table_1 where run_id = ?
union
select * from table_2 where run_id = ?
Is that possible without doing this :
ps.setString(1, runId);
ps.setString(2, runId);
Reusing a PreparedStatementOnce a PreparedStatement is prepared, it can be reused after execution. You reuse a PreparedStatement by setting new values for the parameters and then execute it again.
setString. Sets the designated parameter to the given Java String value. The driver converts this to an SQL VARCHAR or LONGVARCHAR value (depending on the argument's size relative to the driver's limits on VARCHAR values) when it sends it to the database.
Return Values for the executeUpdate Method When the method executeUpdate is used to execute a DDL (data definition language) statement, such as in creating a table, it returns the int value of 0.
Prepared statements are much faster when you have to run the same statement multiple times, with different data. Thats because SQL will validate the query only once, whereas if you just use a statement it will validate the query each time.
This cannot be done with plain JDBC. You could instead use Spring's JDBCTemplate, which would support what you want with Named Parameters, and re-use the same name wherever it's needed in the statement.
See Named parameters in JDBC
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