简体   繁体   English

如何使用 jdbc 驱动程序在 java 中正确执行“SET”查询

[英]how to properly execute a `SET` query in java using jdbc driver

I am able to make a connection to my database but unable to execute a SET query properly.我能够连接到我的数据库,但无法正确执行SET查询。 From looking at the documentation, I should be using execute not executeQuery or executeUpdate .通过查看文档,我应该使用execute而不是executeQueryexecuteUpdate I have a working connection and this is the rest:我有一个工作connection ,这是 rest:

 try (Statement st = connection.createStatement()) {
        boolean result = st.execute("SET search_path TO '712275-8S8DH-74DASS'");
        ResultSet queryResult = st.executeQuery("SELECT MAX(customer.last_updated) from customer");
        while (queryResult.next()) {
          String lastUpdated = queryResult.getString("last_updated");
        }
 } catch (SQLException ex) {
        LOGGER.info(ex.getMessage());
 }

I get these exceptions: The column name last_updated was not found in this ResultSet.我得到了这些异常: The column name last_updated was not found in this ResultSet. and No data from query which makes me think the search_path hasn't been set properly because when I make a direct connection using psql , I am able to get results by running并且No data from query这让我认为 search_path 设置不正确,因为当我使用psql进行直接连接时,我可以通过运行获得结果

postgres=> SET search_path TO '712275-8S8DH-74DASS';
SET
postgres=> SELECT MAX(customer.last_updated) from customer;
[expected result]

Your query doesn't return the result in a column called last_updated .您的查询不会在名为last_updated的列中返回结果。 That's because you are doing an aggregate operation.那是因为您正在执行聚合操作。 I think the column returned by the query is called max .我认为查询返回的列称为max

This might work:这可能有效:

String lastUpdated = queryResult.getString("max");

Or you can use an alias:或者您可以使用别名:

ResultSet queryResult = st.executeQuery("SELECT MAX(customer.last_updated) as last_updated from customer");

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

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