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()
?我將如何減輕這個問題?空指針異常後初始化
你認爲什麼是'的Class.forName( 「com.mysql.jdbc.Driver」)的目的;'? –
如果這是一個jdbc4驅動程序,它應該無關緊要,如果您調用Class.forName或不。堆棧跟蹤有什麼? –