初始化后空指针异常

时间:2014-03-31 18:45:18

标签: java jdbc nullpointerexception

    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上获得空指针异常,即使我在initDbConnection()上调用了test3()?我将如何消除这个问题?

1 个答案:

答案 0 :(得分:2)

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();
}