You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQLAlchemy连接PostgreSQL报错:角色‘postgres’不存在

解决Flask连接PostgreSQL的“角色‘postgres’不存在”错误

问题代码

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:Admin123456%40@localhost/oklondon'
db = SQLAlchemy(app)

class london_companies(db.Model):
    
    __tablename__ = 'london_companies'
    
    company_name = db.Column(db.String, primary_key=True)
    type = db.Column(db.String(50), nullable=False)
    employees = db.Column(db.Integer, nullable=False)
    graduate_schemes = db.Column(db.String(5), nullable=False)
    headquarters = db.Column(db.String(50), nullable=False)

@app.route('/')
def index():
    companies = london_companies.query.all()
    return render_template('index.html', companies=companies)

if __name__ == '__main__':
    app.run(debug=True)

注:代码中存在两处笔误,已修正:_name_改为__name__,tablename改为__tablename__,否则SQLAlchemy无法正常识别。

运行错误信息

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: 角色“postgres”不存在
127.0.0.1 - - [19/Nov/2023 19:13:53] "GET / HTTP/1.1" 500 -

补充说明

  • 实际密码为Admin123456@,已转义为%40
  • 目标用户拥有全部权限:
    用户权限截图

解决方案

1. 检查PostgreSQL中是否存在postgres角色

打开PostgreSQL命令行工具(psql),执行命令查看所有角色:

\du

若没有postgres角色,执行以下命令创建(需超级权限):

CREATE ROLE postgres WITH LOGIN SUPERUSER PASSWORD '你的密码';

2. 替换URI中的正确用户名

如果你的PostgreSQL默认用户名不是postgres(比如部分系统用当前系统用户名作为默认角色),将数据库URI中的postgres替换为实际存在的用户名:

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://你的实际用户名:Admin123456%40@localhost/oklondon'

3. 手动验证数据库连接

通过psql命令测试连接,确认用户名和数据库的有效性:

psql -U postgres -d oklondon -h localhost

若提示数据库不存在,先创建目标数据库:

CREATE DATABASE oklondon;

内容的提问来源于stack exchange,提问作者Saumitra Jagdale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:13:22