statement.executeQuery()之谜。代码未被执行,也没有被捕获例外。

时间:2018-02-08 10:47:41

标签: java sql jdbc prepared-statement executequery

提供代码和输出。搜索了互联网,但没有找到解决方案。所有内容都可以编译并运行正常,直到" // PROBLEMATIC LINE ",执行直接执行到" // HERE &#34 ;没有任何指示,异常或错误。我已经多次使用此代码与SQLServer的jdbc驱动程序并且工作正常,我可能在这里缺少什么?在同一个应用程序中我也使用此代码与mySql jdbc驱动程序,再次,工作正常。就在这段代码中,存在一个问题。显然我使用的是java.sql。*;

try {
        Class.forName(driver);
        setResponse("Failure. 1");
        connectionTest = DriverManager.getConnection(url, username, password);
        setResponse("Failure. 2");
        String query = "SELECT TOP (1) [id] FROM "+ table + ";";
        PreparedStatement statement = connectionTest.prepareStatement(query);
        setResponse("Failure. 3");
        System.out.println(statement);
        ResultSet resultset = statement.executeQuery();  //PROBLEMATIC LINE
        System.out.println("DOES NOT EVEN PRINT THIS");
        setResponse("Failure. 4");
        if (resultset.first()) setResponse("Success.");
        else setResponse("Failure. 5");
        System.out.println("Query success: ");  
        setResponse("Failure. 6");
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        try {
            connectionTest.close();  //HERE
            return getResponse();
        }
        catch (Exception e) {
            e.printStackTrace();
            return getResponse();
        }
    }

输出:

------------------------------------
-------------DATABASES--------------
------------------------------------
SQLServerPreparedStatement:1
Failure. 3
------------------------------------
----------TESTS COMPLETED-----------
------------------------------------

2 个答案:

答案 0 :(得分:1)

抛出异常时,git status块将退出。当try块退出时,将执行try块。由于finally块中有return个语句,因此您永远不会进入finally块。

不要在catch区块中return。然后堆栈跟踪将被打印,您可以处理异常。

答案 1 :(得分:0)

正如其他人所提到的那样,你应该尝试一下尝试捕捉的东西。我的建议:

try {
    Class.forName(driver);
    setResponse("Failure. 1");
    connectionTest = DriverManager.getConnection(url, username, password);
    setResponse("Failure. 2");
    String query = "SELECT TOP (1) [id] FROM "+ table ;
    PreparedStatement statement = connectionTest.prepareStatement(query);
    setResponse("Failure. 3");
    System.out.println(query);
    ResultSet resultset = statement.executeQuery(); 
    while ( resultset.next() {
        System.out.println("only one result because of 'top (1)': " + rs.getInt(1));
    }
     resultset.close();
     statement.close();
     connectionTest.close();        
} catch { SQLException sqlex) {
    System.out.println(getClass().getName() + " SQLException:  " + sqlex.getMessage();
}  catch (Exception e) {
    System.out.println(getClass().getName() + " GenericException:  " + e.getMessage();
     e.printStrackTrace();
}

如果所有需要的库都在类路径中,特别是JDBC-Driver,它应该没问题