无法获得 JDBC 连接;嵌套异常是 java.sql.SQLException - junit eclipse

Could not get JDBC Connection; nested exception is java.sql.SQLException - junit eclipse

在 eclipse 中为我的 spring 项目做 junit 测试时失败了,

Could not get JDBC Connection; nested exception is java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

我已经将 jar 文件添加到库 并设置了 环境变量路径 。但它仍然给出错误。

测试功能如下

@Test
void testSave() {
    dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/contactdb");
    dataSource.setUsername("root");
    dataSource.setPassword("root");

    dao = new ContactDAOImpl(dataSource);

    Contact contact = new Contact("Steve Jobs", "steve@apple.com", "California, USA", "0325698745");
    int result = dao.save(contact);

    assertTrue(result > 0);
}

我的pom.xml文件也附上了。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.codejava.contact</groupId>
  <artifactId>ContactManager</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <release>13</release>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <properties>
    <spring.version>5.9.1.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
        <groupId>org.springframework</groupId> 
        <artifactId>spring-webmvc</artifactId> 
        <version>4.2.2.RELEASE</version> 
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId> 
        <artifactId>spring-orm</artifactId> 
        <version>4.2.2.RELEASE</version> 
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId> 
        <artifactId>javax.servlet-api</artifactId> 
        <version>4.0.1</version> 
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId> 
        <artifactId>jstl</artifactId> 
        <version>1.2</version> 
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.19</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.0</version>
    </dependency>
  </dependencies>
</project>

您不需要以下行来加载驱动程序。

dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

查看 this 了解更多信息。

除此之外,请重置您的数据库 root 密码并重试。