0

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...

ooo
  • 17
  • 1
  • 5
  • Check This http://stackoverflow.com/questions/2839321/java-connectivity-with-mysql/2840358#2840358 and http://stackoverflow.com/questions/2983248/com-mysql-jdbc-exceptions-jdbc4-communicationsexception-communications-link-fai – Shyam Sep 24 '13 at 07:24

2 Answers2

1

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

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

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.

Stanley Stein
  • 397
  • 1
  • 3
  • 17
  • my server version is " 5.1.50-community " witch mysql connector should be download/? – ooo Sep 24 '13 at 08:05
  • Refering [link](http://dev.mysql.com/doc/refman/5.0/en/connector-j-versions.html) Table 20.22. Summary of Connector/J Versions Connector/J version Driver Type JDBC version MySQL Server version Status 5.1 4 3.0, 4.0 4.1, 5.0, 5.1, 5.5, 5.6, 5.7 Recommended version 5.0 4 3.0 4.1, 5.0 Released version 3.1 4 3.0 4.1, 5.0 Obsolete 3.0 4 3.0 3.x, 4.1 Obsolete – Stanley Stein Sep 24 '13 at 08:44
  • 1. Could you utilize the default mysql client (i.e. mysql) to access the local database "test" by the same username and the password? 2. Could you try to stop the local firewall if possible? – Stanley Stein Sep 24 '13 at 09:32
  • i'm developing a java web application in which it should be desplay the my sql open session,so i want access on mysql to show the open sessions – ooo Sep 24 '13 at 09:37
  • Could you try to do the two steps I suggested? as I suspected that test was not accessible. – Stanley Stein Sep 24 '13 at 09:47