Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JDBC与try-with-resources_Java_Jdbc_Try With Resources - Fatal编程技术网

Java JDBC与try-with-resources

Java JDBC与try-with-resources,java,jdbc,try-with-resources,Java,Jdbc,Try With Resources,我正在尝试创建一个集中式类,该类连接并返回SQL查询的ResultSet,这样我就不必每次尝试获取查询时都创建一个新连接 我正在使用try-with-resources,但是,每当我使用try-with-resources时,我都会遇到编译时错误,我不知道为什么 public class JDBC { // logger declaration is omitted private static final String dbURL = "jdbc:oracle:";

我正在尝试创建一个集中式类,该类连接并返回SQL查询的
ResultSet
,这样我就不必每次尝试获取查询时都创建一个新连接

我正在使用
try-with-resources
,但是,每当我使用
try-with-resources
时,我都会遇到编译时错误,我不知道为什么

public class JDBC {

    // logger declaration is omitted

    private static final String dbURL = "jdbc:oracle:";
    private static final String userName = "blah";
    private static final String password = "12345";

    public ResultSet retrieveSQLQuery(String sqlQuery) {            
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;

        try (conn = DriverManager.getConnection(dbUrl, user, password);
             statement = conn.createStatement();
             rs = statement.executeQuery(sqlQuery)) {               

        } catch (SQLException e) {
            logger.info(e.getMessage());
        }                    
        return rs;        
    }
}

您应该这样使用它:

   public ResultSet retrieveSQLQuery(String sqlQuery) {            
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;

        try {      
            conn = DriverManager.getConnection(dbUrl, user, password);
            statement = conn.createStatement();
            rs = statement.executeQuery(sqlQuery);         
        } catch (SQLException e) {
            logger.info(e.getMessage());
        }                     
        return rs; 
    }
它不起作用,因为你把代码放在括号里。你应该把它放在括号里->{}。这也是为什么会出现错误的原因,因为没有一个类有这样的方法:

    try(bla bla bla) {}

Java 7

使用时,必须在
try with resources
块中声明指向
Closeable
资源的变量

此外,返回
rs
是一个坏主意,它将在方法完成后关闭。因此,您可能会在方法外部得到一个
SQLException
(类似于“ResultSet已关闭”)。您应该在
中解析
rs
并尝试使用资源
块,然后从您的方法返回SQL不可知对象:

public ResultSet retrieveSQLQuery(String sqlQuery) {            
    try (Connection conn = DriverManager.getConnection(dbUrl, user, password);
         Statement statement = conn.createStatement();
         ResultSet rs = statement.executeQuery(sqlQuery)) {
        MyResult result = ...; // parse rs here
        return myResult;               
    } catch (SQLException e) {
        logger.info(e.getMessage());
        // return something (empty MyResult or null) from here or rethrow the exception
        // I'd recommend to get rid of this catch block and declare the SQLException on method signature
    }                    
}
您在不正确的
try with resources
语法上遇到编译时错误,仅此而已


更新

Java9 Java 9为
try with resources
提供了更灵活的语法。您可以在
try(…)
块之外声明
Closeable
资源:

public ResultSet retrieveSQLQuery(String sqlQuery) {
    Connection conn = DriverManager.getConnection(dbUrl, user, password);
    try (conn; ResultSet rs = conn.createStatement().executeQuery(sqlQuery)) {
        MyResult result = ...; // parse rs here
        return myResult;               
    } catch (SQLException e) {
        // handle error
    }                    
}

错误是什么?@AlexandruMarina我犯了不少错误。一旦在getConnection上显示
未知类集合
,并且在
语句.executeQuery(sqlQuery)
上出现
未处理sql异常
,您将在关闭结果集后返回结果集。这是行不通的。@NathanHughes-Hmm,那么我怎样才能创建一个jdbc类来动态地从sql查询返回值呢?例如,如果我想查询clob而不是字符串?然后我不必返回一个ResultSet吗?可能您的
JDBC
类应该返回一个对象或集合,其中包含来自ResultSet和close-then连接的then数据。我明白了。嗯,但是我不能返回rs,因为它不在范围内。但是,我刚刚被告知,我不打算返回resultsetEdited,您应该从
try
-blockHmm返回,但是当我从try blockHmm返回时,仍然会出现编译错误哦,这是因为catch block,请参阅更新。最好将您的方法声明为
抛出SQLException
并在外部捕获它。添加更多编辑,返回
rs
是个坏主意,请参阅更新的答案。OP明确要求使用资源语法进行尝试。你应该去读一本最新的语言手册。