在更新项目的python库的时候,更新完毕后使用sqlalchemy执行engine.execute语句的时候报错,然后发现新的sqlalchemy中根本没有这个方法。

1
AttributeError: 'Engine' object has no attribute 'execute'

找了半天原因发现sqlalchemy2.0后取消了engine.execute方法。需要通过Connection中的execute方法去执行sql语句,而且需要通过sqlalchemy.text对象去传递sql语句。好消息是1.0其实并没有放弃更新,这个实际上已经是两个库了,不能算一个东西,就像是python2跟python3的差距一样大。

2.0版本写法如下:

1
2
3
4
5
6
7
from sqlalchemy import create_engine, text

engine = create_engine("配置信息")

sqltext = text("select * from ...;")
conn = engine.connect()
conn.execute(sqltext)