JDBC MySQL自动将localhost转换为127.0.0.1

Len*_*ran 2 java mysql jdbc

我试图通过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);
    }
Run Code Online (Sandbox Code Playgroud)

从日志中:

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)
Run Code Online (Sandbox Code Playgroud)

为什么用127.0.0.1替换localhost?我已经为localhost配置了登录.

ken*_*ntr 5

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

要回答"为什么用127.0.0.1替换localhost?"这个问题:

MySQL文档中,localhost在连接中使用URL意味着您要连接到套接字.使用127.0.0.1意味着您希望通过TCP/IP进行连接.

在Unix上,MySQL程序特别对待主机名localhost,其方式可能与您期望的与其他基于网络的程序相比有所不同.对于与localhost的连接,MySQL程序尝试使用Unix套接字文件连接到本地服务器....要确保客户端与本地服务器建立TCP/IP连接,请使用--host或-h指定主机名值127.0.0.1

根据这个答案,似乎默认情况下JDBC仅支持TCP/IP连接,至少对于某些Java版本而言.原始来源:http://lists.mysql.com/java/8749:

Java本身不支持unix域套接字

所以,我猜测,因为JDBC只通过TCP/IP连接,所以它转换 localhost127.0.0.1内部.

为了解决我的问题:

  • 我在MySQL中授予了权限 user@127.0.0.1
  • 我在连接URL中更改localhost127.0.0.1.