使用JDBC连接到mysql远程数据库?

时间:2012-10-30 23:02:29

标签: java mysql jdbc connection

我是一名java初学者,我正在研究一个使用JDBC连接到远程mysql数据库的简单应用程序。我已经在本地进行了测试,它运行得很好,但我不能让它为我的远程服务器工作。 我不认为它有多大用处,但是代码是:

Connection connection = null;
String dburl = "jdbc:mysql://314159265:3306/Db_Name";
String userName = "user";
String passWord = "password";

    try {
        Class.forName("com.mysql.jdbc.Driver");

        connection = DriverManager.getConnection(dburl, userName, passWord);
        Statement st = connection.createStatement();                                 

        String query = "INSERT INTO Example (`TestColumn`) VALUES('hello')";
        int rsI = st.executeUpdate(query);
        System.out.println("Hi");
        }catch (Exception e) {
        System.out.println(e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
                System.out.println("Database connection terminated");
            } catch (Exception e) { /* ignore close errors */ }
        }
    }

当我运行时,我收到以下消息:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago.The driver has not received any packets from the server.

我很确定它必定是某种服务器配置问题。

 Notes:
 Username, password, IP, database name, etc. are just examples.

2 个答案:

答案 0 :(得分:3)

  1. 这可能是防火墙问题或配置问题。但我认为这根本不是编码问题 - 您需要开始对连接进行故障排除。

  2. 尝试使用第三方客户端应用程序连接到mysql时出现问题。这将指示是否配置为外部访问。虽然它不能确保从外部看到JDBC,但它确实排除了一些潜在的防火墙问题。

  3. 请按照本指南帮助您搞乱配置

  4. Remote MYSQL Database Access

    如果您仍然卡住,可能是编码问题,请查看此页:

    How to connent to a remote mysql database with java?

    P.S。我假设你使用unix作为操作系统。

答案 1 :(得分:-1)

我猜314159265可以被某个地址取代.... 像jdbc:mysql:// localhost:3306 / 或者jdbc:mysql://127.0.0.1:3306 /