用python sqlachemy查询数据库

时间:2019-03-02 20:48:25

标签: python postgresql sqlalchemy

我在本地有postgresql数据库,正在使用以下python代码对其进行查询。

import os

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))


def main():
    flights = db.execute("select origin,destination,duration from flight").fetchall()
    for flight in flights:
        print(f"{flight.origin} to {flight.destination}, is {flight.duration} minutes")


if __name__ == "__main__":
    main()

对于我的情况,我该为 DATABASE_URL 的值做什么?

1 个答案:

答案 0 :(得分:0)

您需要正确设置数据库URL。对于PostgreSQL,它是:

postgresql//user:password@localhost/database_name