完美解决sqlalchemy.exc.ObjectNotExecutableError: Not an executable object

报错的程序如下:

from sqlalchemy import  create_engine
import pandas as pd
engine=create_engine('mysql+pymysql://root:123456@localhost/gpt') #建立mysql引擎
df=pd.read_sql('select * from gpt-last',con=engine.connect()) #读取mysql数据至df

报错sqlalchemy.exc.ObjectNotExecutableError: Not an executable object

然后查询别人的回答,说要import text并且将sql语句字符串转换为可执行语句,故更改代码如下:

import pandas as pd
from sqlalchemy import  create_engine,text

engine=create_engine('mysql+pymysql://root:123456@localhost/gpt') #建立mysql引擎
df=pd.read_sql(text('select * from gpt-last'),con=engine.connect())#读取mysql数据至df

结果报新的错sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError)(1064, "You have an error in your SQL syntax;)提示我的sql语句有错误,但是这条简单的语句怎么会出错?

思考再三,是不是我的表名中含有特殊字符"-"导致出错了?抱着试一试的态度,将mysql中的表名中和sql语句中的"-"都删掉了,如下,果然程序运行成功!!!

import pandas as pd
from sqlalchemy import  create_engine,text

engine=create_engine('mysql+pymysql://root:123456@localhost/gpt') #建立mysql引擎
df=pd.read_sql(text('select * from gptlast'),con=engine.connect())#读取mysql数据至df

你可能感兴趣的:(数据库,mysql,python)