用户'root'@'localhost'的访问被拒绝-无法使用Java应用程序连接到数据库

时间:2018-12-19 22:28:53

标签: java mysql

我在docker中使用ubuntu作为我的基本映像,并且已经安装了mysql 5.7,并且能够通过提供凭据从命令行连接到测试数据库。

root@test:/tmp/test# mysql --version
mysql  Ver 14.14 Distrib 5.7.24, for Linux (x86_64) using  EditLine wrapper

root@test:/tmp/test# mysql -uroot -proot
    mysql: [Warning] Using a password on the command line interface can be insecure.
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 22
    Server version: 5.7.24-0ubuntu0.18.04.1 (Ubuntu)

    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> exit
    Bye

但是,当我尝试运行连接到测试数据库的简单Java应用程序时遇到了问题。这里是我的代码。

import java.sql.*;
class test{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

问题:

root@test:/tmp/test# java -cp "./mysql-connector-java-5.1.39-bin.jar:/tmp/test" test
Wed Dec 19 22:00:05 GMT 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
java.sql.SQLException: Access denied for user 'root'@'localhost'

1 个答案:

答案 0 :(得分:0)

您需要打开网络侦听器。要在所有网络接口上侦听(将其打开到所有网络),您可以:

  1. bind-address设置为0.0.0.0。为此,请编辑my.cnf文件:

    sudo vi /etc/mysql/my.cnf
    

    确保绑定地址未注释(行首没有#)并设置为:

    bind-address            = 0.0.0.0
    
  2. 保存文件,然后重新启动MySQL服务器进程:

    sudo服务mysql重新启动

  3. 或者,您可以重新启动整个服务器。