使用 sqlalchemy 执行原生 sql 报错AttributeError: 'str' object has no attribute '_execute_on_connection' 的解决方案
1、代码如下
import pandas as pd
from sqlalchemy import create_engine, text
# 创建数据库连接引擎
engine = create_engine("mysql+mysqldb://root:admin123@localhost:3306/mydb?charset=utf8")
connection = engine.connect()
sql_query = "SELECT * FROM product_price"
result_set = connection.execute(sql_query) # 错误写法,执行报错AttributeError: 'str' object has no attribute '_execute_on_connection'
result_set = connection.execute(text(sql_query)) # 正确写法
2、执行当前文件报错如下
(priceAnalysisAppEnv389) ➜ utils git:(main) ✗ python pd_import_data.py Traceback (most recent call last): File "/Users/zhangyanli/.pyenv/versions/3.8.9/envs/priceAnalysisAppEnv389/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1417, in execute meth = statement._execute_on_connection AttributeError: 'str' object has no attribute '_execute_on_connection' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "pd_import_data.py", line 12, in <module> result_set = connection.execute(sql_query) File "/Users/zhangyanli/.pyenv/versions/3.8.9/envs/priceAnalysisAppEnv389/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1419, in execute raise exc.ObjectNotExecutableError(statement) from err sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: 'SELECT * FROM product_price'
3、定位问题

4、解决办法

【思考】 在之前的开发过程中我记得是可以使用字符串 sql 去执行的,包括使用单引号/双引号/三引号,而且一些参考解决方案中也是可以的,但是我现在出问题了,不知道是不是在什么时候开始 python或者 sqlalchemy的某个版本之后,执行原生 sql 需要使用 text()包裹。

浙公网安备 33010602011771号