JDBC MySQL 仅在测试中工作 class

JDBC MySQL only working in test class

如题名所述,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();
}