Connect to postgresql: FATAL: database “xxx” does not exist

  • A+
Category:Languages

I'm trying to connect to a local PostgreSQL database using Java, but get 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

 


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; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: