2014-03-31 59 views
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(); 
     } 
    } 

爲什麼我得到空指針異常的conn即使我呼籲test3()initDbConnection()?我將如何減輕這個問題?空指針異常後初始化

+4

你認爲什麼是'的Class.forName( 「com.mysql.jdbc.Driver」)的目的;'? –

+0

如果這是一個jdbc4驅動程序,它應該無關緊要,如果您調用Class.forName或不。堆棧跟蹤有什麼? –

回答

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