[英]How can the java SQL connector be used to connect to a database on a different computer
我的計算機上有一個簡單的數據庫用於測試,我正嘗試從筆記本電腦中檢索數據庫中的某些信息。 因此,我希望我的筆記本電腦發出一個請求,以查看我的計算機MySQL數據庫中的信息。 下面顯示了我嘗試在筆記本電腦上運行的Java代碼,以收集學生表中的第一個條目,該表位於我的計算機上。
我在筆記本電腦和計算機上都安裝了MySQL工作台,如果計算機將存儲數據並且筆記本電腦僅提取數據,是否必須同時在兩台計算機上安裝MySQL工作台。
到目前為止,我從研究中學到的是,應該在URL中使用公共ip,而不是計算機的ip,因此我在其中添加了它,但是在堆棧跟蹤中收到了CommunicationsException和“ Connection timed out”。 我已經通過閱讀這個答案, 這個答案類似的問題,但我難以理解這兩種解決方案,可能有人指我一個初學者指南從遠程使用MySQL數據庫的訪問數據。
public class TestRemote{
//JDBC variables
Connection connection;
Statement statement;
ResultSet resultSet;
//String variables
String url;
String user;
String password;
public static void main(String[] args) {
TestRemote sql = new TestRemote();
ArrayList<String> firstnames = sql.getColumn("students", "firstname", "studentid=4");
System.out.println(firstnames.get(0));
}
// Constructor
public TestRemote()
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("couldnt find class");
}
url = "jdbc:mysql://81.159.3.167:3306/test"; //?autoReconnect=true&useSSL=false";
user = "user";
password = "pass123";
connection = null;
statement = null;
resultSet = null;
}
private void closeConnection(){
try{
if(connection != null)
connection.close();
if(statement != null)
statement.close();
if(resultSet != null)
resultSet.close();
connection=null; resultSet=null; statement=null;
}catch(Exception e){
e.printStackTrace();
}
}
public ArrayList<String> getColumn(String table, String column, String where) {
ArrayList<String> resultsArray = new ArrayList<String>();
try {
connection = DriverManager.getConnection(url, user, password);
statement = connection.createStatement();
if(!where.equals(""))
resultSet = statement.executeQuery("SELECT "+column+" FROM "+table + " WHERE "+where);
else
resultSet = statement.executeQuery("SELECT "+column+" FROM "+table);
while(resultSet.next()) {
String val = resultSet.getString(1);
if(val==null)
resultsArray.add("");
else
resultsArray.add(val);
}
//resultsArray = (ArrayList<String>) resultSet.getArray(column);
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Model.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
closeConnection();
return resultsArray;
}
}
我在筆記本電腦和計算機上都安裝了MySQL工作台,如果計算機將存儲數據並且筆記本電腦僅提取數據,是否必須同時在兩台計算機上安裝MySQL工作台。
沒有所謂的“計算機”就是您的服務器。 它不需要mysql工作台。 它只需要mysql服務器
應在網址中使用公共IP,而不是計算機的IP
數據庫幾乎絕對不應公開在公共IP地址上。 如果兩台計算機都在LAN上,則專用網絡IP是服務器應偵聽的地址,這是連接字符串上應使用的IP。
堆棧跟蹤中的CommunicationsException和“連接超時”
由於服務器未運行,因此無法在該ip:port上進行偵聽或對其進行防火牆丟棄數據包。
您的Java代碼可能很好。 但是問題是,是否在另一台機器上運行並在公用IP上的端口3306上偵聽的MySQL服務器? 默認情況下,它只應偵聽localhost,因此您需要更改MySQL安裝,以便偵聽公共IP。 還要確保沒有防火牆阻止訪問。 嘗試連接筆記本電腦上的工作台,以訪問另一盒上的MySQL服務器。 如果運行此命令,請再次嘗試Java代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.