Ping MySQL Server Using JDBC

后端 未结 3 1112
余生分开走
余生分开走 2021-01-01 19:51

This seems rather simple (not for me)...

How does one ping a mysql server using the JDBC? i have successfully used select and insert queries with JDBC and MySQL, but

3条回答
  •  离开以前
    2021-01-01 20:24

    I don't think there is anything in the JDBC APi for this.

    But you can simply use InetAddress and the isReachable() method to check if the server is there (which is essentially what a ping is doing).

    http://download.oracle.com/javase/6/docs/api/java/net/InetAddress.html#isReachable%28int%29

    Edit:
    If you want to check if MySQL is running rather than pinging the server you could try to open a socket to the server on the MySQL default port.

    Something like this:

    InetAddress addr = InetAddress.getByName("your.server.com");
    int port = 3306;
    SocketAddress sockaddr = new InetSocketAddress(addr, port);
    Socket sock = new Socket();
    sock.connect(sockaddr, 2000); // open the connection with a 2 seconds timeout
    

    If connect() does not throw an exception something is running on port 3306.

    If you want to make sure that it's a MySQL server on that port, the only way is to establish a JDBC connection (but you need a valid username/password for that) and run a statement e.g. the PING statement mentioned by Brian.

提交回复
热议问题