python - 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.
解决方案
由于您没有提供有关要上传到数据库的数据框的任何信息,因此我给您举了一个可行的示例。将其与您所拥有的进行比较:
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
。在上面,数据框看起来像这样
推荐阅读
- python - 在熊猫列表中查找字符串的一部分
- python - 如何按大小过滤数据框字典?
- matlab - 如何在 MATLAB 中生成 Nakagami-m 衰落通道?
- c# - 使用 Selenium C# 为 IWA 应用程序实现模拟
- node.js - 如何在nodeJS中使用异步处理错误?
- csv - 重组这个 csv 最简单的方法是什么?
- python - 在计算机重新启动之前,编辑器中更新的 HTML 代码不会出现在浏览器中
- ios - 在目标 C 中获取 __NSCFString 或 __NSCFString 到 __NSDictionaryI o 数组中的位置
- javascript - 我需要捕获 window.onbeforeunload 事件
- python - 如何在 python 中的进程之间共享数据?