gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 16:31:17 25 4
gpt4 key购买 nike

我使用 ubuntu 作为 docker 中的基础镜像,并且已经安装了 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'

最佳答案

您需要打开网络监听器。要监听所有网络接口(interface)(向所有网络开放),您可以:

  1. 绑定(bind)地址设置为0.0.0.0。为此,请编辑 my.cnf 文件:

    sudo vi /etc/mysql/my.cnf

    其中确保绑定(bind)地址未注释(行开头没有 #)并设置为:

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

    sudo服务mysql重启

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

关于java - 用户 'root' 的访问被拒绝 @'localhost' - 无法使用 java 应用程序连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53860045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com