我正在开发一个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连接被拒绝.检查主机名和端口是否正确
我已经google了它,也看过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.
标签:android,java,postgresql,eclipse,jdbc
来源: https://codeday.me/bug/20191003/1845838.html