Karlx Swanovski
Karlx Swanovski

Reputation: 2989

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

Why I'm getting null pointer exception on conn even though I called the initDbConnection() on test3() ? How will I elimate this problem?

Upvotes: 0

Views: 84

Answers (1)

A Paul
A Paul

Reputation: 8261

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

should be the first line. As this load the mysql driver in the memory. Then you will acquire the connection.

So it should be

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

Upvotes: 2

Related Questions