我已經創建了一個 PostgreSQL 資料庫架構,我想將一個 android 應用程式與資料庫連接。我收到此錯誤:
"W/System.err: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections."
這是我的代碼:
public class Database {
private Connection connection;
private final String host = "localhost";
private final String database = "postgres";
private final int port = 5432;
private final String user = "postgres";
private final String pass = "password";
private String url = "jdbc:postgresql://%s:%d/%s";
private boolean status;
public Database() {
this.url = String.format(this.url, this.host, this.port, this.database);
connect();
//this.disconnect();
System.out.println("connection status:" status);
}
private void connect() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, user, pass);
status = true;
System.out.println("connected:" status);
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
this.status = false;
}
}
public Connection getExtraConnection(){
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
}
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Database db = new Database();
}
}
我找不到任何有助于將 Android 應用程式與本地 PostgreSQL 資料庫連接的任何東西。有什么問題,我該如何解決?
uj5u.com熱心網友回復:
你不見了Class.forName("org.postgresql.Driver"),上面DriverManager.getConnection
uj5u.com熱心網友回復:
localhost:5432可以從設備訪問嗎?如果您在真實設備上進行測驗,您的 PostgreSQL 服務器必須在您的設備網路中,或者如果設備通過 USB 電纜連接,您可以使用 ADB 埠轉發連接到服務器。
uj5u.com熱心網友回復:
嘗試更改替換主機行:
private final String host = "10.0.2.2";
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/396118.html
標籤:爪哇 安卓 PostgreSQL的 安卓工作室 等级
