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();
}
}
即使我在 test3()
上调用了 initDbConnection()
,为什么我在 conn
上遇到空指针异常?我该如何消除这个问题?
最佳答案
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();
}
关于java - 初始化后出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22769670/