简体   繁体   中英

failed to connect to MySql from java

i want to open a MySql connection from java. and this my code :

public static void main(String [] args){
    String line;
    Connection connection;
    Statement statement;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
        connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "manager");
        statement =connection.createStatement();

        System.out.println("Database Created...!!!");
        System.out.println("Connected");


}

but it give me this error:

    com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    Last packet sent to the server was 1 ms ago.
        ...
Caused by: java.net.ConnectException: Connection timed out: connect

why? and what it should be do? please help me. thank you...

This is because your mysql might not be running. Try to telnet by telnet 127.0.0.1 3306 If you get error then mysql is not running for sure. you can also check

netstat -aon | find /i "listening"

this will show all listening ports

It is the connection problem between the driver and the server. Please ensure that the driver version and the server version match. For example, if your server version is MySQL 4.0 or 3.23, you should use mysql-connector-java-3.0.11-stable-bin.jar instead of the latest version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM