在PreparedStatement中重用参数?

l0r*_*c10 5 java sql oracle prepared-statement

我将参数传递给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);
    }
}
Run Code Online (Sandbox Code Playgroud)

查询看起来像这样:

select * from table_1 where run_id = ?
Run Code Online (Sandbox Code Playgroud)

现在我想像这样修改我的查询,并重用第一个参数(两者?都使用runId参数):

select * from table_1 where run_id = ?
union
select * from table_2 where run_id = ?
Run Code Online (Sandbox Code Playgroud)

没有这样做可能是这样的:

ps.setString(1, runId);
ps.setString(2, runId);
Run Code Online (Sandbox Code Playgroud)

Nic*_*ckJ 9

使用普通JDBC无法做到这一点.您可以改为使用Spring的JDBCTemplate,它可以支持您想要的命名参数,并在语句中的任何位置重用相同的名称.

请参阅JDBC中的命名参数