我正在开发一个android应用程序,我需要连接到Postgresql数据库,我安装了它9.3版本,并在PGAdminIII中检查它正在连接。我还在 eclipse 中创建了一个 java 项目,只是为了测试 JDBC,它连接成功,但是当我尝试从 Android 项目连接到 Postgresql 时,它抛出错误:org.postgresql.util.PSQLException:连接尝试失败。 这是我在 MainActivity.java 中编写的代码
@Override
protected Void doInBackground(Void... params) {
try {
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.43.207:5432/testdb", "postgres", "password");
System.out.println("connection success");
conn.close() ;
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
和pg_hba.conf
IPv4 本地连接:
托管所有 192.168.43.207 信任
IPv6 本地连接:
托管所有所有::1/128 信任
postgresql.conf
listen_addresses = '*'
注意:如果我使用 localhost/127.0.0.1 更改 IP 地址 192.168.43.207,则会抛出错误 - org.postgresql.util.psqlException 连接被拒绝。检查主机名和端口是否正确 我用谷歌搜索过它,也看到了 Stackoverflow 上的帖子,但没有任何作用。 我使用的是windows7,请根据它提供解决方案。 请帮助我,因为我在过去的两天里一直在努力,但没有任何效果。
编辑:当我在 Windows 中从 CMD 运行这些命令时,我得到了以下输出
C:\Windows\system32>sc query postgresql-9.3
SERVICE_NAME: postgresql-9.3
TYPE : 10 WIN32_OWN_PROCESS
STATE : 4 RUNNING
(STOPPABLE, PAUSABLE, ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
C:\Windows\system32>netstat -a | findstr 5432
TCP 0.0.0.0:5432 -PC:0 LISTENING
TCP [::]:5432 -PC:0 LISTENING
TCP [::1]:5432 -PC:49573 ESTABLISHED
TCP [::1]:5432 -PC:49574 ESTABLISHED
最佳答案
您的问题是 Android 上的 127.0.0.1
会转到虚拟 Android 设备,而不是托管 PostgreSQL 数据库的计算机。引用Android emulator documentation for networking :
Each instance of the emulator runs behind a virtual router/firewall service that isolates it from your development machine's network interfaces and settings and from the internet. An emulated device can not see your development machine or other emulator instances on the network. Instead, it sees only that it is connected through Ethernet to a router/firewall.
在其下方,有一个虚拟路由器表:
下面是关于使用 127.0.0.1
的部分(强调我的):
Also note that the address 127.0.0.1 on your development machine corresponds to the emulator's own loopback interface. If you want to access services running on your development machine's loopback interface (a.k.a. 127.0.0.1 on your machine), you should use the special address 10.0.2.2 instead.
如果您想连接到开发计算机,则应使用 10.0.2.2
而不是 127.0.0.1
。
关于java - Postgresql 未使用 JDBC 连接到 android,抛出 org.postgresql.util.PSQLException : The connection attempt failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27592881/