-1

我正在尝试使用 Java 代码连接到 WAMP 服务器中的 MySql db。服务器位于本地网络内的机器中。以下是我使用的代码:

public class MySQLAccess {

public static void main(String args[]) {

      String url = "jdbc:mysql://192.168.0.21:3306/";
      String dbName = "mydb";
      String driver = "com.mysql.jdbc.Driver";
      String userName = "root"; 
      String password = "";
      try {
      Class.forName(driver).newInstance();
      Connection conn = DriverManager.getConnection(url+dbName,userName,password);
      System.out.println("Connected to the database");
      conn.close();
      System.out.println("Disconnected from database");
      } catch (Exception e) {
      e.printStackTrace();
      }

我得到以下异常:

com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: 

** BEGIN NESTED EXCEPTION ** 

java.net.ConnectException
MESSAGE: Connection timed out

STACKTRACE:

java.net.ConnectException: Connection timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at java.net.Socket.<init>(Socket.java:366)
at java.net.Socket.<init>(Socket.java:209)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:271)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at MySQLAccess.main(MySQLAccess.java:24)


** END NESTED EXCEPTION **



    Last packet sent to the server was 1 ms ago.
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2847)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at MySQLAccess.main(MySQLAccess.java:24)

在这段代码中我看不到任何明显的东西会导致这个异常。此外,我再次确认端口号正确且主机没有任何防火墙。

什么可能是此问题的原因以及可能的解决方案。任何 melp 都非常感谢。

4

1 回答 1

1

1.检查你的mysql是否在特定的主机和端口上运行

2.尝试从您的代码正在运行的机器上ping该主机以确保连接(防火墙??)

3.如果你有 db ui工具或其他工具,请尝试使用该工具进行连接

于 2013-01-17T10:50:04.617 回答