我正在嘗試編寫一些從我的個人計算機連接到遠程數據庫的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)
你可以在你的問題中加上你的'ssh'命令嗎? – Serge
ssh [email protected]。我在公共和私人授權之後使用這個來自膩子。 – trevdro