繁体   English   中英

初始化后空指针异常

[英]Null pointer exception after initialize

    private static String dbURL = "jdbc:mysql://localhost:3306/mydb";
    private static String username = "secret";
    private static String password = "secret";
    private static Connection conn = null;

    public static void initDbConnection(){
        try {
            conn = DriverManager.getConnection(dbURL, username, password);
            Class.forName("com.mysql.jdbc.Driver");
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void test3(){
        initDbConnection();
        try{
            String sql = "SELECT * FROM Products";
            Statement statement = conn.createStatement();
            ResultSet result = statement.executeQuery(sql);
            while (result.next()){
                String name = result.getString("name");
                System.out.println(name);
            }
        } 
        catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

为什么我在conn上得到空指针异常,即使我在test3()上调用了initDbConnection() test3() 我将如何消除这个问题呢?

Class.forName("com.mysql.jdbc.Driver");

应该是第一行。 因为这会在内存中加载mysql驱动程序。 然后你将获得连接。

所以它应该是

try {
     Class.forName("com.mysql.jdbc.Driver");
     conn = DriverManager.getConnection(dbURL, username, password);
} catch (SQLException e1) {
     e1.printStackTrace();
}
 catch (ClassNotFoundException e) {
     e.printStackTrace();
}

暂无
暂无

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

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