Spring Boot应用连接PostgreSQL失败:报错FATAL: database does not exist
Hey there, let's work through this common database connection snag together. Here are the most likely fixes to get your Spring Boot app connected to PostgreSQL smoothly:
1. Confirm the database actually exists in PostgreSQL
PostgreSQL won't automatically create databases for you—you need to set it up manually.
- Use the
psqlcommand line tool: runcreatedb your_database_name(replace with the exact name you planned to use) - Or use pgAdmin: right-click on "Databases" > "Create" > "Database" and input the name that matches your app's configuration
2. Double-check your Spring Boot database config
Head to your application.properties or application.yml and verify these critical values:
For application.properties:
spring.datasource.url=jdbc:postgresql://localhost:5432/your_database_name spring.datasource.username=your_db_username spring.datasource.password=your_db_password spring.jpa.hibernate.ddl-auto=update # Adjust to your preferred schema management setting
Key reminder:
The database name in spring.datasource.url must exactly match the one you created in PostgreSQL. PostgreSQL is case-sensitive if you created the database with quoted names (e.g., "TowerDB" vs towerdb). If you used quotes during creation, add them to the URL: jdbc:postgresql://localhost:5432/"TowerDB"
3. Ensure your database user has access permissions
Even if the database exists, your configured user might not have rights to access it. Run this command in psql (as a superuser like postgres):
GRANT ALL PRIVILEGES ON DATABASE your_database_name TO your_db_username;
4. Verify PostgreSQL dependency is in your pom.xml
Make sure the correct JDBC driver is included—your generated pom should have this, but it's worth double-checking:
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency>
5. Test the connection outside Spring Boot
Rule out Spring-specific issues by testing the connection directly with psql:
psql -h localhost -p 5432 -U your_db_username -d your_database_name
If this fails, the problem lies with your PostgreSQL setup, not your Spring app.
Start with step 1 and work your way down—this error almost always comes down to a mismatch between your app's configuration and the actual state of your PostgreSQL instance.
内容的提问来源于stack exchange,提问作者Michu93

