JDBC-postgres,连接被拒绝

时间:2009-08-18 19:05:46

标签: postgresql jdbc

这是我第一次使用java访问数据库,所以我在这里可能有一个简单的错误,但是当我从远程数据库中检索我的连接时,我可以访问,但是我拒绝连接。

以下是相关代码:

String url = "jdbc:postgresql:url.isformatted.like.this/database";

try {
    conn = DriverManager.getConnection(url, "username", "password");
} catch (SQLException e) {
    e.printStackTrace();
    System.exit(1);
}

(为了隐私起见,删除了用户/通行证和数据库网址)

问题不能是凭据或URL本身,因为我使用它来使用psql从同一个盒子手动登录。我在想它可能是URL的格式,但是我找不到任何在远程地址上使用psql的例子(它们都是本地主机的东西)

3 个答案:

答案 0 :(得分:12)

根据http://www.petefreitag.com/articles/jdbc_urls/有效网址

jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database
jdbc:postgresql://host:port/database?user=userName&password=pass
jdbc:postgresql://host:port/database?charSet=LATIN1&compatible=7.2

你在主持人面前有这个吗?

答案 1 :(得分:1)

我同意@Jonathan关于在类路径上使用PostgreSQL JDBC jar库:这是我使用的:

private static final String TABLE_NAME = "tablenamegoeshere";
private static final String DRIVER = "org.postgresql.Driver";
private static final String URL = "jdbc:postgresql://url.for.database/DatabaseName";
private static final String USERNAME = "yourusername";
private static final String PASSWORD = "yourpassword";


private static Connection getConnection() throws Exception {
  Class.forName(DRIVER);
  Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
  return conn;
}

答案 2 :(得分:0)

我只是查看了连接到PostgreSQL数据库的代码,看起来像这样:

DriverManager.getConnection(String.format("jdbc:postgresql://%s/%s", server, dbName), userName, password);

另外,请确保在尝试连接之前加载PostgreSQL数据库驱动程序:

Class.forName("org.postgresql.Driver");

并且PostgreSQL JDBC Jar库位于类路径中。