Flask+SQLAlchemy连接PostgreSQL报错:players数据库不存在
解决方案
1. 创建players数据库
你能通过终端连接PostgreSQL服务器,但服务器内尚未创建players数据库,需手动完成创建:
- 直接用终端命令创建:
createdb -U postgres players
- 或者进入PostgreSQL交互模式创建:
psql -U postgres
在交互界面输入以下SQL命令后退出:
CREATE DATABASE players; \q
2. 修正数据库URI配置
- 确保URI前缀为
postgresql://(SQLAlchemy 1.4+已弃用postgres://格式) - 把
%password%替换为你实际的PostgreSQL密码,比如密码为mypassword,配置应为:
app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://postgres:mypassword@localhost:5432/players'
- 如果终端连接用的是5433端口,此处端口号也要同步改为5433
3. 初始化数据库表
数据库创建完成后,需要生成对应的players表:
- 打开Flask shell:
flask shell
- 在shell中执行表创建命令:
from app import db db.create_all()
- 也可以在
app.py中添加初始化代码(需放在db.init_app(app)之后):
with app.app_context(): db.create_all()
额外检查
- 确认PostgreSQL服务处于运行状态:Linux下执行
sudo systemctl start postgresql,Windows则在系统服务列表中启动PostgreSQL服务 - 确保
postgres用户拥有创建数据库和表的权限
内容的提问来源于stack exchange,提问作者Kripke
相关产品推荐
相关产品推荐

