0
    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?

2
  • 4
    What do you think is the purpose of Class.forName("com.mysql.jdbc.Driver");? Commented Mar 31, 2014 at 18:46
  • if this is a jdbc4 driver it shouldn't matter if you call Class.forName or not. what's in the stacktrace? Commented Mar 31, 2014 at 18:51

1 Answer 1

2
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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.