【问题标题】:Reuse a parameter in a PreparedStatement?在 PreparedStatement 中重用参数?
【发布时间】:2015-08-10 15:48:41
【问题描述】:

我正在将参数传递给 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);
    }
}

查询看起来像这样:

select * from table_1 where run_id = ?

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

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

不这样做有可能吗:

ps.setString(1, runId);
ps.setString(2, runId);

【问题讨论】:

  • 离题:在 C/C++ 的情况下是可能的。函数 OCIDefineByPos、OCIDefineByName 的行为符合预期。我认为在 JDBC 的情况下,为了与不支持它的数据库兼容,牺牲了这个特性。所以也许 Oracle JDBC 驱动程序有一些专有的扩展。

标签: java sql oracle prepared-statement


【解决方案1】:

以下内容适用于 oracle。但是,如果表很大,这可能不是一个好的选择。

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

【讨论】:

    【解决方案2】:

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

    Named parameters in JDBC

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-04
      • 1970-01-01
      • 2023-04-08
      • 2011-03-07
      • 2021-11-12
      • 2011-06-09
      相关资源
      最近更新 更多