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

问题描述 投票:0回答:1

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

无法获得JDBC连接;嵌套的异常是java.sql.SQLException:用户'root'@'localhost'的访问被拒绝(使用密码:是)

我已经将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", "[email protected]", "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>
java mysql eclipse junit jar
1个回答
0
投票

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

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

检查this了解更多信息。

除此之外,重设数据库root密码,然后重试。

© www.soinside.com 2019 - 2024. All rights reserved.