python-3.x 为什么不能使用sqlalchemy“如果数据库不存在就创建数据库”?

r6hnlfcb  于 2023-05-30  发布在  Python
关注(0)|答案(1)|浏览(195)

bounty已结束。此问题的答案有资格获得+50声望奖励。赏金宽限期9小时后结束。showkey正在寻找一个答案从一个有信誉的来源

我根据示例写了一些行到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.

那怎么修?

uoifb46i

uoifb46i1#

通过升级解决:

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),成功!

相关问题