首页 > 解决方案 > 创建引擎对象以连接postgresql数据库时出现Python sqlalchemy错误?

问题描述

我在 python 中使用 sqlalchemy 连接到 PostgreSQL 数据库中的数据库,但出现错误。谁能帮帮我吗。

这是运行文件后的命令行输出。

C:\Users\naeem\Desktop>python sql.py

Traceback (most recent call last):

  File "sql.py", line 5, in <module>
    engine = create_engine("postgressql://postgres:postgres@localhost:5432/flights")
  File "<string>", line 2, in create_engine

  File "C:\Program Files\Python37\lib\site-packages\sqlalchemy-1.4.0b1.dev0-py3.7-win-amd64.egg\sqlalchemy\util\deprecations.py", line 171, in warned
    return fn(*args, **kwargs)

  File "C:\Program Files\Python37\lib\site-packages\sqlalchemy-1.4.0b1.dev0-py3.7-win-amd64.egg\sqlalchemy\engine\create.py", line 437, in create_engine
    entrypoint = u._get_entrypoint()

  File "C:\Program Files\Python37\lib\site-packages\sqlalchemy-1.4.0b1.dev0-py3.7-win-amd64.egg\sqlalchemy\engine\url.py", line 172, in _get_entrypoint
    cls = registry.load(name)

  File "C:\Program Files\Python37\lib\site-packages\sqlalchemy-1.4.0b1.dev0-py3.7-win-amd64.egg\sqlalchemy\util\langhelpers.py", line 278, in load
    "Can't load plugin: %s:%s" % (self.group, name)

sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgressql

这是我的 sql.py 的 python 代码

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

engine = create_engine("postgressql://postgres:postgres@localhost:5432/flights")

db = scoped_session(sessionmaker(bind=engine))
flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall()
for flight in flights:
    print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.")

标签: pythonpostgresqlsqlalchemy

解决方案


I think you misspelled postgres in your "create_engine" function you put 2 s characters instead of 1

example:

from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine("postgresql://postgres:postgres@localhost:5432/flights")

db = scoped_session(sessionmaker(bind=engine))
flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall()
for flight in flights:
   print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.")```

推荐阅读