Java 连接到 postgresql:致命:数据库“xxx”不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54491559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Connect to postgresql: FATAL: database "xxx" does not exist
提问by harvestnight
I'm trying to connect to a local PostgreSQL database using Java, but gets org.postgresql.util.PSQLException: FATAL: database "xxx" does not exist
我正在尝试使用 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);
}
}
}
Database "xxx" exists. And in pgAdmin4 and psql
it connected fine. I even used python
and it worked fine:
数据库“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()
I've updated pg_hba.conf
and set it to this:
我已经更新pg_hba.conf
并将其设置为:
host all all 127.0.0.1/32 trust
Tried show ports
(if this helps), got 5432
尝试过show ports
(如果这有帮助),得到5432
UPDATE
更新
Tried some answers: changing localhost
to 127.0.0.1
>>> not working.
尝试了一些答案:更改localhost
为127.0.0.1
>>> 不起作用。
And there's only one instance of postgreSQL(port 5432) is in listening...
并且只有一个 postgreSQL(端口 5432)实例正在监听...
btw I changed the db name xxx
to postgres
in my codes because that's a default db(I guess?) and it should exists anyhow, but got the same error...
顺便说一句,我在我的代码中更改了数据库名称xxx
,postgres
因为这是默认数据库(我猜?),无论如何它应该存在,但得到了相同的错误...
PROBLEM SOLVED
问题解决了
See my comment below
看我下面的评论
回答by prasad_
Here is the Java JDBC code to connect to an existing database (example PosrgresSQL 10.5). Make sure the the database is already created (use psql
commands to verify, see below) and the driver is in the path (example driver: postgresql-42.2.4.jar
).
这是连接到现有数据库的 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);
Use psql
command line toolto work with the database:
使用psql
命令行工具处理数据库:
\list -- list all databases
\connect test_db -- connect to a database
To drop and create the database:
要删除和创建数据库:
DROP DATABASE IF EXISTS test_db;
CREATE DATABASE test_db;
回答by Sergey Gurin
try to check if there is only one instanceof PostgreSQL by using:
尝试使用以下方法检查是否只有一个PostgreSQL实例:
netstat -vanp tcp | grep 5432