连接到postgresql:严重:数据库“ xxx”不存在

时间:2019-02-02 09:04:58

标签: java postgresql

我正在尝试使用Java连接到本地PostgreSQL数据库,但得到org.postgresql.util.PSQLException: FATAL: database "xxx" does not exist

public class TestDemo {
    public static void main(String args[]) {
        Connection connection = null;
        try {
            Class.forName("org.postgresql.Driver");
            connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/xxx","postgres", "Dlsdb@123");
            connection.close();
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
    }
}

数据库“ xxx”存在。在pgAdmin4和psql中,它连接良好。我什至使用了python,它运行良好:

def test():
    conn = psycopg2.connect(database="xxx", user="postgres", password="Dlsdb@123", host="127.0.0.1", port="5432")
    print "Opened database successfully"
    conn.close()

我已更新pg_hba.conf并将其设置为此:

host    all    all    127.0.0.1/32   trust

尝试过show ports(如果有帮助),得到了5432


更新

尝试了一些答案:将localhost更改为127.0.0.1 >>>不起作用。

只有一个postgreSQL(端口5432)实例正在监听...

btw我在代码中将数据库名称xxx更改为postgres,因为这是默认数据库(我想是吗?),它应该存在,但还是有同样的错误...


解决的问题

在下面查看我的评论

2 个答案:

答案 0 :(得分:0)

尝试使用以下方法检查PostgreSQL是否仅存在一个实例

netstat -vanp tcp | grep 5432

答案 1 :(得分:-1)

这是连接到现有数据库的Java JDBC代码(示例PosrgresSQL 10.5)。确保数据库已经创建(使用psql命令进行验证,请参见下文)并且驱动程序在路径中(示例驱动程序:postgresql-42.2.4.jar)。

String url = "jdbc:postgresql://localhost/test_db?user=postgres&password=master";
Connection conn = DriverManager.getConnection(url);

使用psql 命令行工具来处理数据库:

\list                   -- list all databases
\connect test_db        -- connect to a database

要删除并创建数据库:

DROP DATABASE IF EXISTS test_db;
CREATE DATABASE test_db;