【发布时间】:2020-11-09 11:02:42
【问题描述】:
我试图将 DataFrame 保存到 mysql 表中,出现以下代码错误:TypeError: The first argument to execute must be a string or unicode query.
engine2=sqlalchemy.create_engine('mysql+pyodbc://user:pwd@localhost/sakila?DRIVER={MySQL ODBC 8.0 Unicode Driver}?charset=utf8')
df.to_sql('test12',engine2,index=False)
我找不到解决办法,我该怎么办?
更新: df:
cnxn2=pyodbc.connect('DRIVER={MySQL ODBC 8.0 Unicode Driver};SERVER=localhost;DATABASE=sakila;UID=user;PWD=pwd')
df=pd.read_sql("select * from actor",cnxn2)
错误:
TypeError Traceback (most recent call last)
<ipython-input-12-0c720eb43923> in <module>()
1 engine2=sqlalchemy.create_engine('mysql+pyodbc://root:Johnny2010@localhost/sakila?DRIVER={MySQL ODBC 8.0 Unicode Driver}?charset=utf8')
----> 2 df.to_sql('test',engine2,index=False)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in to_sql(self, name, con, schema, if_exists, index, index_label, chunksize, dtype)
2125 sql.to_sql(self, name, con, schema=schema, if_exists=if_exists,
2126 index=index, index_label=index_label, chunksize=chunksize,
-> 2127 dtype=dtype)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\sql.py in to_sql(frame, name, con, schema, if_exists, index, index_label, chunksize, dtype)
448 pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index,
449 index_label=index_label, schema=schema,
--> 450 chunksize=chunksize, dtype=dtype)
...
...
C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py in _execute_context(self, dialect, constructor, statement, parameters, *args)
1191 statement,
1192 parameters,
-> 1193 context)
C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\default.py in do_execute(self, cursor, statement, parameters, context)
506 def do_execute(self, cursor, statement, parameters, context=None):
--> 507 cursor.execute(statement, parameters)
TypeError: The first argument to execute must be a string or unicode query.
【问题讨论】:
-
什么是```test12´´´?尝试提供您的 ´´´df´´´ 样本以进行重现。
-
test12是mysql中的表名,之前没有创建过,是不是应该先创建表再插入dataframe?