代码之家  ›  专栏  ›  技术社区  ›  showkey

为什么不能使用sqlalchemy“创建不存在的数据库”?

  •  -1
  • showkey  · 技术社区  · 2 年前

    我写了几行给 create database if not exists 根据样品:

    https://www.programcreek.com/python/example/98164/sqlalchemy_utils.database_exists

    from sqlalchemy import create_engine
    from sqlalchemy_utils import database_exists, create_database
    db_user = 'postgres'
    db_pass = 'xxxxxx'
    db_ip = '127.0.0.1'
    db_name = 'mydb'
    engine = create_engine('postgresql://{}:{}@{}/{}/'.format(db_user,db_pass,db_ip,db_name))
    if not database_exists(engine.url): create_database(engine.url)
    

    它遇到错误:

    Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
      File "/home/debian/.local/lib/python3.9/site-packages/sqlalchemy_utils/functions/database.py", line 569, in create_database
        quote(engine, database),
      File "/home/debian/.local/lib/python3.9/site-packages/sqlalchemy_utils/functions/orm.py", line 528, in quote
        dialect = get_bind(mixed).dialect
      File "/home/debian/.local/lib/python3.9/site-packages/sqlalchemy_utils/functions/orm.py", line 339, in get_bind
        raise TypeError(
    TypeError: This method accepts only Session, Engine, Connection and declarative model objects.
    

    那该怎么修呢?

    0 回复  |  直到 2 年前
        1
  •  2
  •   showkey    2 年前

    通过升级解决:

    pip  install  --upgrade  sqlalchemy-utils
    Found existing installation: SQLAlchemy-Utils 0.39.0
    Uninstalling SQLAlchemy-Utils-0.39.0:
      Successfully uninstalled SQLAlchemy-Utils-0.39.0
    Successfully installed sqlalchemy-utils-0.41.1
    

    重新运行上一个 if not database_exists(engine.url): create_database(engine.url) 成功