正如题名所说,JDBC似乎只在测试类中起作用,无法解释原因。
public static Connection getConnection()
{
try {
String connectionString = "jdbc:mysql://localhost/" + database + "?" +
"user=" + sqlUser + "&password=" + sqlPassword;
return DriverManager.getConnection(connectionString);
} catch (SQLException ex) {
Logger.getLogger(ConnectionLoader.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
以下测试通过:
assertNotNull("Connection must not be null.", ConnectionLoader.getConnection());
但是在调试项目时失败并出现 SQLException 提示找不到合适的驱动程序。
这是我在 Netbeans 中的项目的屏幕截图,如您所见,我在库中包含了 mysql jar。
我错过了什么吗?
最佳答案
需要加载MySQL驱动。
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://x.x.x.x:3306/databasename", "username", "password");
...
}catch(Exception ex){
ex.printStackTrace();
}
关于java - JDBC MySQL 仅在测试类中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31109384/