Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse a parameter in a PreparedStatement?

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);
like image 851
l0r3nz4cc10 Avatar asked May 28 '15 08:05

l0r3nz4cc10


People also ask

Can a PreparedStatement be reused?

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.

Which are the parameters setString () method?

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.

What does PreparedStatement executeUpdate return?

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.

Which is faster statement or PreparedStatement?

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.


1 Answers

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

like image 65
NickJ Avatar answered Nov 09 '22 12:11

NickJ