java - JDBC MySQL 仅在测试类中工作

标签 java mysql jdbc junit

正如题名所说,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。

我错过了什么吗?

enter image description here

最佳答案

需要加载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/

相关文章:

php - 根据条件创建mysql更新字符串

java - mysql jdbc 驱动程序无法识别 latin1 字符

java - 使用 BatchUpdateExcpetion 处理 JDBC BatchUpdate 异常

java - 用于最终确定 CheckpointMark 的 Beam 模型合约

java - 编写一个程序,要求用户输入一个整数 (n) 并打印 n 行输出

java - 将变量与整数进行比较时,!= 运算符似乎不起作用

mysql - GROUP_CONCAT WHERE 子句

java - PowerMock PrepareForTest 注释导致 AmazonSQSClient 构造函数出现问题

java - Spring boot 无法验证新建立的连接

java - JDBC 可调用语句中的 'call' 是什么意思?