简体   繁体   English

在 PreparedStatement 中重用参数?

[英]Reuse a parameter in a PreparedStatement?

I am passing a parameter to a PreparedStatement like this :我将一个参数传递给 PreparedStatement 这样的:

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) :现在我想修改我这样的查询,并重新使用第一个参数(包括?将使用的runid参数):

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);

This cannot be done with plain JDBC.这不能用普通的 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.您可以改为使用 Spring 的 JDBCTemplate,它将支持您想要的命名参数,并在语句中的任何需要的地方重新使用相同的名称。

See Named parameters in JDBC请参阅JDBC 中的命名参数

The following works fine with oracle.以下适用于 oracle。 However it may not be a good choice if the tables are huge.但是,如果桌子很大,这可能不是一个好的选择。

Select * from ( SELECT ? run_id FROM DUAL ) A
JOIN (  select * from table_1
        union
        select * from table_2 
     ) B ON A.run_id = B.run_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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