2017-05-12 75 views
0

我無法連接遠程數據庫。當我在本地主機上連接我自己的數據庫時,它會連接。怎麼了?連接被拒絕:連接,無法連接數據庫mysql

Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database! 

    Caused by: 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. 

Caused by: java.net.ConnectException: Connection refused: connect 

Java代碼:

String url = "jdbc:mysql://ipadress:3306/database?autoReconnect=true&useSSL=false"; 
     String username = "username"; 
     String password = "password"; 
     String query = "SELECT * FROM database"; 

     System.out.println("Connecting database..."); 
      try { 
     // The newInstance() call is a work around for some 
     // broken Java implementations 

     Class.forName("com.mysql.jdbc.Driver").newInstance(); 
    } catch (Exception ex) { 
     // handle the error 
    } 
     try (Connection connection = DriverManager.getConnection(url, username, password)) { 
      System.out.println("Database connected!"); 
      //Uruchamiamy zapytanie do bazy danych 
         Statement stmt = connection.createStatement(); 
         ResultSet rs = stmt.executeQuery(query); 

         while (rs.next()) { 

         } 

         connection.close(); 
     } catch (SQLException e) { 
     throw new IllegalStateException("Cannot connect the database!", e); 
     } 
    } 

我可以登錄到數據庫上的phpMyAdmin,我沒有root帳戶,這是我朋友的數據庫。我檢查了端口3306是否打開:http://www.yougetsignal.com/tools/open-ports/,它已關閉。我可以在哪裏打開它?在「端口轉發」中的路由器設置?我應該設置什麼專用IP和類型(TCP或UDP)來打開此端口?

+0

可能你可以分享你的代碼嗎? –

+0

正確提到的遠程數據庫的URL和憑證? –

+0

是的,他們是 我改變了他們,因爲我不想分享我的數據庫地址 – Jkrr

回答

0

(道歉,如果這個答案是不完整的,但就是不適合評論太多)

1)不要忽視例外。這很糟糕:// handle the errorcatch塊中沒有其他東西,如果出現錯誤,您的代碼將不報告錯誤,並且繼續執行(它應該退出/ break/return,具體取決於那段代碼在哪裏)。我覺得檢查"SHOW GLOBAL VARIABLES LIKE 'PORT';"是不夠的。詢問你的朋友,數據庫守護進程實際上是否監聽到你可以連接的網絡接口上的3306端口。 MySQL可以配置禁用網絡(skip-networking)或啓用,但僅適用於本地計算機(bind-address=127.0.0.1localhost - 應該是bind-address=0.0.0.0bind-address=hostname或公共IP地址...)。

要自己檢查,如果您在linux上,請嘗試使用nctelnet(如果您沒有它,請安裝nc):nc remotehost 3306。如果你得到「拒絕連接」,那麼錯誤肯定不在你的java代碼中,而是在服務器設置中。

+0

「SHOW GLOBAL VARIABLES LIKE'PORT';」現在是3306,我會請他去做這些事情。我更新了我的問題,請檢查它。 – Jkrr

+0

我的意思是我認爲檢查這是不夠的,他需要用我提到的鍵檢查my.cnf配置文件。將編輯澄清。 –

+0

那麼,3306端口是否在我的路由器中關閉? – Jkrr

相關問題