从其他电脑连接到本地 Mysql 服务器

Connecting to local Mysql server from other pc

我有一台安装了 apache 和 mysql 服务器的本地服务器。他们两个都很好用。我可以在浏览器上正常显示 apache 默认页面。我可以通过终端管理 mysql 数据库。目前一切正常。但是如果我尝试编写代码来使用我的数据库。它给我通信 link 错误。

这是简单的 JAVA 代码:

public static void main(String[] args) {

        String url = "jdbc:mysql://192.168.1.49:3306/test";
        String username = "root";
        String password = "1234";

        System.out.println("Connecting database...");
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);

            System.out.println("Database connected!");
        } catch (SQLException e) {
            throw new IllegalStateException("Cannot connect the database!", e);
        }

    }

这里是错误:

正在连接数据库...

Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database! at servermysql.ServerMysql.main(ServerMysql.java:34) Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

服务器是 UBUNTU14.04 服务器

谢谢朋友们

您必须将 MYSQL 绑定地址设置为 0.0.0.0,因为它通常只在 127.0.0.1 上默认执行以下命令:

sed -i -e”s/^bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/” /etc/mysql/my.cnf 

或在/etc/mysql/my.cnf中手动将绑定地址更改为0.0.0.0并重新启动MYSQL。