简体   繁体   中英

Connecting to MySQL DB in Java

I am running a database through 000WebHosting.com. When I try to connect to my database, I get the following error:

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.

This is my code:

String url = "jdbc:mysql://" + "mysql2.000webhost.com/";
try
{
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection conn = DriverManager.getConnection(url + "DB_NAME", userName, passWord);
} 
catch (InstantiationException | IllegalAccessException | SQLException e)
{
    System.out.println(e);
}

And the exception continues to arise on the conn line.

What am I doing wrong?

Try to initilize your db connection like this (put your db name in the URL):

final static String HOSTNAME = "yourdomain.com";
final static String PORT = "3306";
final static String USER = "youruser";
final static String PWD = "yourpassword";
final static String DBNAME = "dbname";

public java.sql.Connection setupConnection() {

    java.sql.Connection conn = null;

    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    System.out.println("Connection is being established...");

    String url = "jdbc:mysql://" + HOSTNAME + ":" + PORT + "/" + DBNAME +
                "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
    try {
        conn = DriverManager.getConnection(url, USER, PWD);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    System.out.println("Database connection successfully established!");

    return conn;
}
  1. Check whether your MySQL database server is hosted/up/on.
  2. Check if the username and password entered of the connecting database is correct.
  3. Check if you have include the MySQL jar file in your build path and lib folder of your web server eg Tomcat
  4. Check the URL of the connecting database is correct.

Also do this changes and see

String url = "jdbc:mysql://mysql2.000webhost.com/";

Also I found this

MySQL from 000webhost doesn't allow you to connect from external applications, just from within pages hosted in their domain.

Please check: How can I connect to MySQL from my computer?

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