gpt4 book ai didi

java - JDBC MySQL自动将localhost转为127.0.0.1

转载 作者:行者123 更新时间:2023-11-29 01:21:50 25 4
gpt4 key购买 nike

我正在尝试通过 localhost 从 JDBC 连接到 MySQL。但是连接失败。在异常情况下,我看到 JDBC 正在尝试连接到 127.0.0.1

    String connectionString = "";
try {
loadProperties();
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connectionString = "jdbc:mysql://" + properties.getProperty("host") + "/" + properties.getProperty
("database") + "?user=" + properties.getProperty("user") + "&password=" + properties
.getProperty
("password");
connect = DriverManager
.getConnection(connectionString);
logger.debug("Connected to " + properties.getProperty("host"));
} catch (Exception e) {
logger.error("Database Connection failed with connection string - " + connectionString,e);
}

来自日志:

Database Connection failed with connection string - jdbc:mysql://localhost/testdb?user=testuser&password=testpass

java.sql.SQLException: Access denied for user 'testuser'@'127.0.0.1' (using password: YES)

为什么将 localhost 替换为 127.0.0.1?我只为本地主机配置了登录。

最佳答案

我遇到同样的问题时偶然发现了这个问题。

要回答“为什么要用 127.0.0.1 替换本地主机?”这个问题:

来自MySQL docs ,在您的连接 URL 中使用 localhost 意味着您想要连接到一个套接字。使用 127.0.0.1 表示您希望通过 TCP/IP 进行连接。

On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. ... To ensure that the client makes a TCP/IP connection to the local server, use --host or -h to specify a host name value of 127.0.0.1

根据 this answer ,似乎默认情况下 JDBC 仅支持 TCP/IP 连接,至少对于某些 Java 版本是这样。原始出处:http://lists.mysql.com/java/8749 :

Java itself doesn't support unix domain sockets

因此,我猜测由于 JDBC 仅通过 TCP/IP 连接,它在内部将 localhost 转换为 127.0.0.1

解决我的问题:

  • 我在 MySQL 中为 user@127.0.0.1 授予了权限
  • 我将连接 URL 中的 localhost 更改为 127.0.0.1

关于java - JDBC MySQL自动将localhost转为127.0.0.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19479938/

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