[英]Connecting to MySQL DB in Java
我正在通過000WebHosting.com運行數據庫。 當我嘗試連接到數據庫時,出現以下錯誤:
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.
這是我的代碼:
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);
}
在conn
線上繼續出現例外。
我究竟做錯了什么?
嘗試像這樣初始化您的數據庫連接(在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;
}
還要進行此更改並查看
字符串url =“ jdbc:mysql://mysql2.000webhost.com/”;
我也發現了這個
000webhost中的MySQL不允許您從外部應用程序進行連接,而只能從其域中托管的頁面內進行連接。
請檢查: 如何從計算機連接到MySQL?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.