AttributeError:尝试在 python 中运行 sqlalchemy 来管理我的 SQL 数据库时,“Engine”对象没有属性“execute”

nov*_*aly 19 python mysql sql sqlalchemy

我有以下代码行不断给我一个错误,即引擎对象没有对象执行。我认为我一切都对,但不知道接下来会发生什么。似乎其他人也遇到了这个问题,重新启动他们的笔记本电脑就可以了。我正在使用 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)
Run Code Online (Sandbox Code Playgroud)

小智 37

从 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)
Run Code Online (Sandbox Code Playgroud)

所以现在正确的代码执行方式是:

with engine.connect() as conn:
    result = conn.execute(stmt)
Run Code Online (Sandbox Code Playgroud)

源代码此处描述了 1.4 中的行为此处描述了 2.0 中的行为

  • 它们是否故意让动态查询变得更加困难? (2认同)

小智 7

sql = f"""INSERT INTO user_apis
  (api_id, user_id, monthly_requests, total_requests)
  VALUES (1, {current_user.id}, 0, 0)"""
Run Code Online (Sandbox Code Playgroud)

1.x

result = db.engine.execute(sql)
Run Code Online (Sandbox Code Playgroud)

2.x

from sqlalchemy import text
with db.engine.begin() as conn:
    result = conn.execute(text(sql)) 
    conn.commit()              #2.x execute now only works with SELECT.
                               #Inserts, Updates and Deletes now must be 
                               #in a transaction and explicitly committed
                               #use engine echo=True to show transaction status
Run Code Online (Sandbox Code Playgroud)

选择 SQL

with db.engine.connect() as conn:
    result = conn.execute(text(sql)).fetchall()
Run Code Online (Sandbox Code Playgroud)