首页 > 解决方案 > df.to_sql(TypeError:要执行的第一个参数必须是字符串或 unicode 查询。)

问题描述

我试图将 DataFrame 保存到 mysql 表,以下代码发生错误:TypeError:要执行的第一个参数必须是字符串或 unicode 查询。

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)

在此处输入图像描述

错误:</p>

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.

标签: pythonmysqlpandas

解决方案


由于您没有提供有关要上传到数据库的数据框的任何信息,因此我给您举了一个可行的示例。将其与您所拥有的进行比较:

import numpy as np
import pandas as pd

from sqlalchemy import create_engine
df = pd.DataFrame(np.random.rand(5,3))
df2 = df.where(df < .2, None)
DF = df2.fillna(value=np.nan)
DF = DF.rename(columns = {0:'a', 1:'b',2:'c'})
csv_database = create_engine('sqlite:///csv_database.db', echo=False)
DF.to_sql("FACTS2", if_exists = 'replace',con=csv_database)

所以,你的test12就是我的FACTS2。在上面,数据框看起来像这样

在此处输入图像描述


推荐阅读