【问题标题】:querying database with python sqlachemy使用 python sqlalchemy 查询数据库
【发布时间】:2019-03-03 10:20:41
【问题描述】:

我的本​​地有 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()

我为 mycase 的 DATABASE_URL 的值添加了什么??

【问题讨论】:

  • 你在使用任何数据库系统吗?如果不使用 sqlite,它将数据存储在 .db 文件中。 DATABASE_URL 应该是 sqlite:///tmp/test.db
  • 我正在使用 postgresql
  • 所以使用:postgresql//user:password@localhost/database_name
  • 它不工作,但是当我删除 'os.getenv' 时,它工作
  • 我认为是因为您没有正确设置环境变量DATABASE_URL。您可以省略它,并直接设置它。很高兴它成功了。

标签: python postgresql sqlalchemy


【解决方案1】:

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

postgresql//user:password@localhost/database_name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 2011-10-08
    • 1970-01-01
    • 2019-10-16
    • 2020-01-28
    • 2018-10-06
    • 2021-09-22
    相关资源
    最近更新 更多