有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

postgresql本地java程序无法连接到本地数据库

我无法连接到Pg Admin 4上的数据库;尽管能够在intellij中使用DB Browser查询数据库。下面是我不断遇到的错误

这个程序可以连接到数据库,但是在尝试下载python sql工具后,出现了一些问题。我重新安装了postgresql并创建了原来的表,但现在无法连接到它们

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

这是connectionclass。试图访问数据库的java

public class ConnectionClass {

    public Connection connection;
    public Connection getConnection() {
        String dbName = "users";
        String userName = "postgres";
        String password = "pass";

        
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            connection = DriverManager.getConnection("jdbc:mysql://localhost:5432/" + dbName, userName, password);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
}

最后,我有一个sql查询工具的截图

DB Browser

我已经检查了几十个这样的错误,但它们似乎都与拼写错误有关。我可以将数据库更改为不正确的名称、所有者或密码,但错误保持不变。我想这可能是我使用mysql-connector-java-8.0.20时的驱动程序。jar,但postgresql是运行数据库的。我试着用postgresql-42.2.17替换jar。但那也不行

此时此刻,我正在考虑放弃整件事,搬到一座山上生活,所以任何帮助都是感激的

编辑:在使用the method outlined here解包之前,将jar压缩到lib文件夹中是不起作用的。可能需要几次尝试,但我的终于奏效了。非常感谢!如果我有任何声望点,我会投票


共 (1) 个答案

  1. # 1 楼答案

    下载合适的驱动程序

    https://jdbc.postgresql.org/download.html

    加载“正确的”驱动程序“”组织。postgresql。在你的程序中,就像你在mysql上做的那样,改为这样做

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

    并使用正确的协议“jdbc:postgresql:”

    Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/" + dbName, userName, password);