我正在编写一个查询 PostgreSQL 数据库的 Java 程序。我正在关注这个例子,但在这里遇到了麻烦:
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/testdb", "mkyong",
"123456");
根据DriverManager 的 JavaDoc,第一个字符串是“表单的数据库 url jdbc:subprotocol:subname
。当我连接到服务器时,我输入psql -h dataserv.abc.company.com -d app -U emp24
并提供密码qwe123
(例如缘故)。第一个参数应该getConnection
是什么?
我试过了
connection = DriverManager.getConnection(
"jdbc:postgresql://dataserv.abc.company.com", "emp24",
"qwe123");
并得到运行时错误:no suitable driver found
.
我已经下载了 JDBC4 Postgresql 驱动程序,版本 9.2-1000。
在我修复我的程序以加载驱动程序后,Class.forName("org.postgresql.Driver");
它可以识别 JDBC URL,但它仍然无法连接。我现在有一个新错误。
当我运行程序时出现错误,这是带有堆栈跟踪的输出:
-------- PostgreSQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
Connection Failed! Check output consoleorg.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:207)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:65)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:140)
at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:21)
at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:31)
at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:23)
at org.postgresql.Driver.makeConnection(Driver.java:393)
at org.postgresql.Driver.connect(Driver.java:267)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DatabaseConnect.main(DatabaseConnect.java:32)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.postgresql.core.PGStream.<init>(PGStream.java:60)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:101)
... 11 more
我将 URL 格式化为getConnection
:
"jdbc:postgresql://dataserv.abc.company.com:5432/app"