Reputation: 71
I'm trying to connect to a local PostgreSQL database using Java, but gets 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:
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:
host all all 127.0.0.1/32 trust
Tried show ports
(if this helps), got 5432
UPDATE
Tried some answers: changing localhost
to 127.0.0.1
>>> not working.
And there's only one instance of postgreSQL(port 5432) is in listening...
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...
PROBLEM SOLVED
See my comment below
Upvotes: 6
Views: 35831
Reputation: 1573
try to check if there is only one instance of PostgreSQL by using:
netstat -vanp tcp | grep 5432
Upvotes: 0
Reputation: 14317
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
).
String url = "jdbc:postgresql://localhost/test_db?user=postgres&password=master";
Connection conn = DriverManager.getConnection(url);
Use psql
command line tool to work with the database:
\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;
Upvotes: 1