我使用的是mysql5.7.21,我用cmd都能够正常的登录和使用MySQL,但是用Java连接时之前还好好的,之后就一直报java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)的错误。网上也找了好多,什么授权,跳过密码重置之类的都试了,还是不行。这是代码:
package com.company;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLTest {
public static void main(String[] args) {
final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/system_log?useUnicode=true&characterEncoding=utf8";
final String USER = "root";
final String PASS = "hwy981220";
Connection con = null;
try {
Class.forName(JDBC_DRIVER);
try {
con = DriverManager.getConnection(DB_URL,USER,PASS);
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} catch (ClassNotFoundException e) {
System.out.println("找不到驱动");
e.printStackTrace();
}
}
}
运行后显示:
运行之后就会显示这样的报错:
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:833)
at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:453)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at com.company.MySQLTest.main(MySQLTest.java:19)
在cmd中都是正常的
C:\WINDOWS\system32>mysql -uroot -p
Enter password: *********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.7.21 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
请问该如何解决
1、com.mysql.jdbc.Driver和mysql-connector-java 5一起用。com.mysql.cj.jdbc.Driver和mysql-connector-java 6 一起用。
因为你的数据库是5.7的,我不知道你的驱动的jar包是什么版本,所以你先把你的的驱动换成com.mysql.jdbc.Driver试一下。
2、如果上面的办法不行的话,你重启一下你的数据库,看是否连接数过多
localhost:3306
连接字符串改为:
127.0.0.1:3306
试试
如果可以登录进去,可能是localhost和127.0.0.1密码不一致的问题,你可以这么理解root@localhost和root@127.0.0.1是两个数据库账户。