场景:使用 sqlalchemy+pandas

1.  'OptionEngine' object has no attribute 'execute'

import pandas as pd
from sqlalchemy import create_engine, text engine = create_engine('mysql+pymysql://root:root1234@127.0.0.1:3308/beststock')
sql = "select max(id) as maxrid FROM tspro_stock_basic " df = pd.read_sql(sql, engine)
print(df)

Error: 提示报错信息:

Traceback (most recent call last):
File "C:\Users\Google_he\PycharmProjects\trunk\PyStock\UnitTest\Test_Sqlalchemy.py", line 15, in <module>
df = pd.read_sql(sql, engine)
File "D:\Program Files (x86)\Python39\lib\site-packages\pandas\io\sql.py", line 591, in read_sql
return pandas_sql.read_query(
File "D:\Program Files (x86)\Python39\lib\site-packages\pandas\io\sql.py", line 1561, in read_query
result = self.execute(*args)
File "D:\Program Files (x86)\Python39\lib\site-packages\pandas\io\sql.py", line 1406, in execute
return self.connectable.execution_options().execute(*args, **kwargs)
AttributeError: 'OptionEngine' object has no attribute 'execute'

排查:

查看 pd.read_sql 的 python 源码,原来,需要传递的是一个 connection,

def read_sql(
sql,
con,
index_col: str | list[str] | None = None,
coerce_float: bool = True,
params=None,
parse_dates=None,
columns: list[str] | None = None,
chunksize: int | None = None,
) -> DataFrame | Iterator[DataFrame]:

打印 传递的 engine 类型

print(type(engine))
// <class 'sqlalchemy.engine.base.Engine'>
// 原来对象传递错了,建立 connection,可以通过 engine.connect() 方法 print(type(engine.connect()))
<class 'sqlalchemy.engine.base.Connection'>

所以,需要改成

import pandas as pd
from sqlalchemy import create_engine, text engine = create_engine('mysql+pymysql://root:root1234@127.0.0.1:3308/beststock')
sql = "select max(id) as maxrid FROM tspro_stock_basic " # df = pd.read_sql(text(sql), con=engine.connect()) df = pd.read_sql(sql, engine.connect())
print(df)

2. 'str' object has no attribute '_execute_on_connection'

改成上面的代码后,出现了下面的错误

Traceback (most recent call last):
File "D:\Program Files (x86)\Python39\lib\site-packages\sqlalchemy\engine\base.py", line 1410, 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 "C:\Users\Google_he\PycharmProjects\trunk\PyStock\UnitTest\Test_Sqlalchemy.py", line 16, in <module>
df = pd.read_sql(sql, engine.connect())
File "D:\Program Files (x86)\Python39\lib\site-packages\pandas\io\sql.py", line 591, in read_sql
return pandas_sql.read_query(
File "D:\Program Files (x86)\Python39\lib\site-packages\pandas\io\sql.py", line 1561, in read_query
result = self.execute(*args)
File "D:\Program Files (x86)\Python39\lib\site-packages\pandas\io\sql.py", line 1406, in execute
return self.connectable.execution_options().execute(*args, **kwargs)
File "D:\Program Files (x86)\Python39\lib\site-packages\sqlalchemy\engine\base.py", line 1412, in execute
raise exc.ObjectNotExecutableError(statement) from err
sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: 'select max(id) as maxrid FROM tspro_stock_basic '

继续查看 read_sql() 的源码,关于入参 sql 的注释及示例

sql : str or SQLAlchemy Selectable (select or text object)
SQL query to be executed or a table name.

再次改成下面,还是错误依旧

df = pd.read_sql("select max(id) as maxrid FROM tspro_stock_basic ", engine.connect())

确定是 入参 sql 的类型有问题,再次看到上面有提到的 text object,看来还是需要转换一下

import pandas as pd
from sqlalchemy import create_engine, text engine = create_engine('mysql+pymysql://root:root1234@127.0.0.1:3308/beststock')
sql = "select max(id) as maxrid FROM tspro_stock_basic " df = pd.read_sql(text(sql), con=engine.connect())
print(df) ---- output ----
maxrid
0 5066

sqlalchemy+pandas:错误 'OptionEngine' object has no attribute 'execute','str' object has no attribute '_execute_on_connection'的更多相关文章

  1. Django2.2报错 AttributeError: 'str' object has no attribute 'decode'

    准备将 Django 连接到 MySQL,在命令行输入命令 python manage.py makemigrations 后报错: AttributeError: 'str' object has ...

  2. Django项目与mysql交互进行数据迁移时报错:AttributeError: 'str' object has no attribute 'decode'

    问题描述 Django项目启动,当我们执行命令 python manage.py makemigrations 出现如下错误: File , in last_executed_query query ...

  3. 解决编码问题:AttributeError: 'str' object has no attribute 'decode'

    1. 问题发现: 出现:读取文件,对其进行解码,出现错误,AttributeError: 'str' object has no attribute 'decode' 解释:属性错误,str对象不包含 ...

  4. Django 运行报异常:AttributeError: 'str' object has no attribute 'get'

    Technorati Tags: Python,Django,Web 在使用django.contrib.auth用户机制进行用户的验证.登录.注销操作时,遇到这个异常. 首先是写了一个登录的视图,要 ...

  5. Python PyInstaller 打包报错:AttributeError: 'str' object has no attribute 'items'

    pyinstaller打包时报错:AttributeError: 'str' object has no attribute 'items' 网上查询,可能是setuptools比较老: 更新一下 p ...

  6. 【Python-遇到的Error】AttributeError: 'str' object has no attribute 'input_text'

    学习类的实例化的时候遇到了AttributeError: 'str' object has no attribute 'input_text', 以下是报错的代码及修改正确的代码. class shu ...

  7. python2 'str' object has no attribute 'decode'

    '.decode('hex') 上述代码,报错: 'str' object has no attribute 'decode' 查找原因: https://stackoverflow.com/ques ...

  8. python3.x运行的坑:AttributeError: 'str' object has no attribute 'decode'

    1.Python3.x和Python2.X版本有一些区别,我遇到了两个问题如下: a.第一个报:mysqlclient 1.3版本不对: 解决办法:注释掉这行即可: b.第二个报:字符集的问题: 报错 ...

  9. python自动化测试,读取excal数据报"'str' object has no attribute 'items'"问题解决

    通过python进行自动化测试,为了方便,对代码和数据进行了分离,此处把测试数据放到了excal表格中.requests.post请求时报"'str' object has no attri ...

  10. Django项目启动 AttributeError: ‘str‘ object has no attribute ‘decode‘ 问题

    Watching for file changes with StatReloader Performing system checks... System check identified no i ...

随机推荐

  1. JZOJ 7339.改试卷

    \(\text{Solution}\) 又忘了线段树分治!! 显然维护一个上凸包 发现加点和删点可以变成限制存在时间 然后把点放在线段树上,线段树下标表示时间 加点时先把点按横坐标排序,然后就可以单调 ...

  2. JZOJ 2934. 【NOIP2012模拟8.7】字符串函数

    题目大意 个等长的由大写英文字母构成的字符串 \(a\) 和 \(b\),从 \(a\) 中选择连续子串 \(x\),从 \(b\) 中选出连续子串y. 定义函数 \(f_{x,y}\) 为满足条件 ...

  3. Ubuntu安装Zabbix6.0

    环境 系统:Ubuntu 20.04 虚拟平台:Vmware Workstation 16 PRO 软件版本:Zabbix 6.0 LTS 数据库:PostgreSQL Web服务:Apache 新建 ...

  4. ES6中的class对象和它的家人们

    在ES6中新增了一个很重要的特性: class(类).作为一个在2015年就出了的特性, 相信很多小伙伴对class并不陌生.但是在日常开发中使用class的频率感觉并不高(可能仅限于作者),感觉对c ...

  5. DIV 阴影

    <div class="div">111</div> .div { width:200px; height:200px; box-shadow: 0 0 1 ...

  6. LeetCode-537 复数乘法

    来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/complex-number-multiplication 题目描述 复数 可以用字符串表示,遵循 ...

  7. 08. AssetBundle.LoadFromFile

    参数 path 文件在磁盘上的路径. crc 未压缩内容的 CRC-32 校验和(可选).如果该参数不为零,则加载前将内容与校验和进行比较,如果不匹配则给出错误. offset 字节偏移(可选).该值 ...

  8. bootstrapTable的一些属性

    url : 'firmSoftTable.action', // 请求后台的URL(*) method : 'post', // 请求方式(*)post/get contentType: " ...

  9. Mysql去重获取最新的一条数据

    Mysql去重获取最新的一条数据 select * from yjzt_kindergartens r where id in (select max(id) from yjzt_kindergart ...

  10. Chrome浏览器崩溃

    1.使用Win+R打开运行对话框,输入regedit,点击确定打开注册表: 2.找到"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome&q ...