在使用Python中的SQLAlchemy管理我的SQL数据库时,尝试运行时出现AttributeError: 'Engine' object has no attribute 'execute'错误。

17

我有以下一行代码,它一直给我一个错误:Engine对象没有执行对象。我认为我的所有东西都正确,但不知道发生了什么事情。似乎其他人也遇到了这个问题,重新启动笔记本电脑可以解决。我正在使用Pycharm,并已重新启动,但未解决任何问题。非常感谢您的帮助!

import pandas as pd
from sqlalchemy import create_engine, text
import sqlalchemy
import pymysql


masterlist = pd.read_excel('Masterlist.xlsx')

user = 'root'
pw = 'test!*'
db = 'hcftest'

engine = create_engine("mysql+pymysql://{user}:{pw}@localhost:3306/{db}"
                           .format(user=user, pw=pw, db=db))


results = engine.execute(text("SELECT * FROM companyname;"))

for row in results:
    print(row)

1
你需要使用engine.connect()。 它是惰性的,并且只有在需要时才会真正连接。 - roganjosh
with engine.connect() as conn: - roganjosh
顺便提一句,如果你想要一个相当不错基于Python的图形用户界面(GUI)的MySQL编辑器, Oracle创建了一个免费的称为MySQL Workbench,它可以让数据库工作像玩Excel一样简单。除非你只是在做概念验证,否则你可能会想研究一下这个工具并节省大量时间。 - easleyfixed
啊 - 完全错过了那个。谢谢! - novawaly
3个回答

33

从1.4版本到2.0版本发生了变化。我相信,上述代码在sqlalchemy 1.4版本中可以正常运行。设置SQLALCHEMY_WARN_20=1 python并运行上述代码会显示以下警告:

<stdin>:1: RemovedIn20Warning: The Engine.execute() method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. All statement execution in SQLAlchemy 2.0 is performed by the Connection.execute() method of Connection, or in the ORM by the Session.execute() method of Session. (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9)

因此,现在正确的代码编写方式是:

with engine.connect() as conn:
    result = conn.execute(stmt)

来源 此处描述了1.4版的行为此处描述了2.0版的行为


1
他们是故意让动态查询变得更困难了吗? - undefined
1
一个好消息是,新的代码with ... as conn可以在1.x和2.x版本中使用,所以你不需要在所有地方都更新代码,避免引发一连串的代码更新问题,至少目前还不需要。 - undefined

4
sql = f"""INSERT INTO user_apis
  (api_id, user_id, monthly_requests, total_requests)
  VALUES (1, {current_user.id}, 0, 0)"""

1.x

result = db.engine.execute(sql)

2.x

with db.engine.begin() as conn:
    result = conn.execute(text(sql))

选择 SQL

with db.engine.connect() as conn:
    result = conn.execute(text(sql)).fetchall()

1
from .. import db

def get():

    sql_statement = \
        """
            SELECT *
        """

    with db.engine.begin() as conn:
        response = conn.exec_driver_sql(sql_statement).all()
    
    return response

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接