我正在尝试连接到本地MySQL服务器,但我一直收到错误.
这是代码.
public class Connect {
public static void main(String[] args) {
Connection conn = null;
try {
String userName = "myUsername";
String password = "myPassword";
String url = "jdbc:mysql://localhost:3306/myDatabaseName";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Database connection established");
} catch (Exception e) {
System.err.println("Cannot connect to database server");
System.err.println(e.getMessage());
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
System.out.println("Database Connection Terminated");
} catch (Exception e) {}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
和错误:
Cannot connect to database server …Run Code Online (Sandbox Code Playgroud) 我连接到MySQL数据库的程序运行正常.然后,在不更改用于设置连接的任何代码的情况下,我得到以下异常:
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.
Run Code Online (Sandbox Code Playgroud)
发生了什么?
用于获取连接的代码:
private static Connection getDBConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
String username = "user";
String password = "pass";
String url = "jdbc:mysql://www.domain.com:3306/dbName?connectTimeout=3000";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
Run Code Online (Sandbox Code Playgroud)