如何在executeQuery上修复此NullPointerException?

时间:2019-05-27 15:58:31

标签: java sqlite jdbc

我的简单sql语句的executeQuery上存在NullPointerException;我认为问题出在与sqlite的连接上,但我无法解决...

我的java方法:

    public Connection connect() throws SQLException {
    Connection conn = null;
    try {
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String url = "jdbc:sqlite:sakila.db.sqlite3";
        conn = DriverManager.getConnection(url);
        System.out.println("Connection to SQLite has been established.");
    } catch (SQLException e) {  
        System.out.println(e.getMessage());  
    } finally {  
        try {  
            if (conn != null) {  
                conn.close();  
            }  
        } catch (SQLException ex) {  
            System.out.println(ex.getMessage());  
        }  
    }
    Statement stmt = conn.createStatement();        
    String sql = "SELECT * FROM FILM LIMIT 10";
    stmt.executeQuery(sql);
    return conn;
}

这是控制台的结果

Connection to SQLite has been established.
Exception in thread "main" java.lang.NullPointerException
at org.sqlite.Stmt.executeQuery(Stmt.java:121)
at Connect.connect(Connect.java:33)
at Main.main(Main.java:10)

预先感谢

2 个答案:

答案 0 :(得分:3)

您的finally块,关闭了连接,所以当语句

Statement stmt = conn.createStatement(); 
达到

时,将抛出NullPointerException。要解决此问题,您的代码应如下所示:

public Connection connect() throws SQLException {

        Connection conn = null;
        try {
            try {
                Class.forName("org.sqlite.JDBC");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            String url = "jdbc:sqlite:sakila.db.sqlite3";
            conn = DriverManager.getConnection(url);
            System.out.println("Connection to SQLite has been established.");
            Statement stmt = conn.createStatement();        
            String sql = "SELECT * FROM FILM LIMIT 10";
            stmt.executeQuery(sql);
            return conn;
        } catch (SQLException e) {  
            System.out.println(e.getMessage());  
        } finally {  
            try {  
                if (conn != null) {  
                    conn.close();  
                }  
            } catch (SQLException ex) {  
                System.out.println(ex.getMessage());  
            }  
        }
    }

答案 1 :(得分:1)

看起来像是在使用连接之前即将关闭连接。尝试在try-catch中移动语句+ executeQuery