2016-05-17 118 views
0

我正在嘗試編寫一些從我的個人計算機連接到遠程數據庫的Java代碼。我目前可以使用私人/公共密鑰授權ssh到這些機器。我可以通過創建SSH隧道(使用Putty)來訪問這些機器的GUI。通過SSH連接防火牆後面的遠程數據庫

我不認爲問題出在我的代碼上,因爲我可以使用MySQL Workbench創建數據庫,並且可以成功查詢數據庫。當試圖訪問數據庫時,我使用了與用於GUI的相同的tunnell地址。所以我的問題是如何連接到數據庫?任何人都可以解釋我的問題嗎?我的代碼發佈在下面。

import java.sql.Connection;   
import java.sql.Statement;  
import java.sql.ResultSet;  
import java.sql.DriverManager;  
import java.sql.SQLException;  
public class SQLConnector {     
     public static void main(String[] args) throws ClassNotFoundException, SQLException {             
       //Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name"   
       String dbUrl = "jdbc:mysql://localhost:9092/db";     

       //Database Username  
       String username = "root"; 

       //Database Password  
       String password = "root";    

       //Query to Execute  
       String query = "select * from employee;"; 

       //Load mysql jdbc driver   
       Class.forName("com.mysql.jdbc.Driver");   

       //Create Connection to DB  
       Connection con = DriverManager.getConnection(dbUrl,username,password); 

       //Create Statement Object  
       Statement stmt = con.createStatement();     

       // Execute the SQL Query. Store results in ResultSet   
       ResultSet rs= stmt.executeQuery(query);       

       // While Loop to iterate through all data and print results  
       while (rs.next()){ 
          String myName = rs.getString(1);           
          String myAge = rs.getString(2);             
          System. out.println(myName+" "+myAge);  
        }  
       // closing DB Connection  
       con.close();    
     } 
} 

我得到的錯誤是:

Exception in thread "main" 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. 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
+0

你可以在你的問題中加上你的'ssh'命令嗎? – Serge

+0

ssh [email protected]。我在公共和私人授權之後使用這個來自膩子。 – trevdro

回答

1

這也許應該是一個評論,但我的名譽犯規讓徵求意見。我敢冒險猜測服務器網絡上的端口阻塞了該端口(不管你使用的是哪個端口),但是允許使用ssh。這個服務器/你在哪裏可以改變任何防火牆上的設置以允許連接?

+0

我想可能是對的。即使我在putty上打開連接(這意味着我可以訪問隧道GUI),我仍然在猜測。我無法通過工作臺訪問,有任何建議嗎? – trevdro

+0

這取決於你的設置是什麼。如果這是Amazon Web Services服務器上的服務器,則必須執行一組步驟以允許訪問端口。如果這是一個坐在同一個網絡上的窗口盒,你必須進入控制面板>>防火牆,然後制定一個允許訪問該端口的規則。基本上,有硬件防火牆和軟件防火牆,並且都必須有一條規則:「請求入站端口####可以,將它傳遞給服務器。」你可以在本地服務器和你的服務器之間提供完整的硬件和軟件設置嗎? – vath

0

如果我明白你的意思,mysql正在使用ssh連接的主機在端口9092上偵聽。

然後用這個SSH命令連接:

ssh -L9092:localhost:9092 [email protected] 

它在本地計算機和隧道在遠程機器上創建一個TCP監聽套接字端口9092在本地機器的端口9092的任何連接

編輯: 我錯過了你使用的膩子。然後打開連接設置對話框,然後瀏覽至ssh並找到port forwarding。這個符號幾乎是一樣的:本地端口,到遠程站點的一些ip:port:here你可以找到一個帶有屏幕截圖的分步指南

+0

我應該在膩子上運行這個ssh -L9092:localhost:9092 [email protected]嗎? – trevdro

+0

-L9092:localhost:9092命令沒有找到,當我在膩子中運行這個。 – trevdro

+0

看到最後編輯 – Serge