intellij idea 添加 mysql 连接器到项目库

intelij idea adding mysql connector to project library

我正在尝试将 mysql 数据库连接到我的 java 项目,但出现错误:java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

如图所示,我在我的项目中添加了mysql-connector-java-5.1.48.jar,但仍然报错。

public static Connection getConnection(){
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException ex) {
            throw new RuntimeException("Error connecting to the database", ex);
        } catch (IllegalAccessException | ClassNotFoundException | InstantiationException e) {
            e.printStackTrace();
        }
        return null;}
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:291)
    at DatabaseAccess.DbConnection.getConnection(DbConnection.java:17)
    at DatabaseAccess.DbConnection.main(DbConnection.java:27)

如果您使用的是 Maven,请将其添加到您的 <dependencies> 标签中:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.19</version>
</dependency>

对于 gradle:

compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.19'