Java app:连接到PostgreSQL数据库

问题描述 投票:0回答:2

我正在尝试连接到postgresQL数据库。通常情况下,我只需转到链接即可连接:

test.ischool.testU.edu

我通过输入我的凭据连接到phpPgAdmin,然后我可以从侧面选择连接到我的数据库testDB。

这是我的相关Java代码:

    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }

    String url = "jdbc:postgresql://test.ischool.testU.edu:5432/testDB";
    String user = "testuser";
    String pass = "testpassword";
    Connection db = null;
    try {
        db = DriverManager.getConnection(url,user,pass);
    } catch (SQLException e1) {
        e1.printStackTrace();
    }

我收到以下错误:

org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port             are correct and that the postmaster is accepting TCP/IP connections.

我很确定我做错了什么。假设我的代码是正确的(我确定不是这种情况),要连接到数据库,我是否需要将我的.jar文件放在远程目录中,或者我可以在本地运行它?这有什么不同吗?

我使用以下python代码成功连接到我的数据库(此代码直接插入远程并从那里运行):

    conn = psycopg2.connect("dbname=testDB user=testuser password=testpassword")
java sql postgresql jdbc
2个回答
0
投票

您使用的JDBC URL是针对MySQL的:

jdbc:mysql://test.ischool.testU.edu:5432/testDB

使用一个用于PostgreSQL:

jdbc:postgresql://test.ischool.testU.edu:5432/testDB

如果更改此功能无效,请发布您获得的确切错误。


0
投票

试试这段代码:

String url = "jdbc:postgresql://localhost/YOURSCHEMA?user=YOURUSER&password=YOURPWD";

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

Connection con = DriverManager.getConnection(url);`
© www.soinside.com 2019 - 2024. All rights reserved.