【发布时间】:2021-12-31 07:40:47
【问题描述】:
我想使用以下代码将 pandas 数据框插入 MySQL 表中。
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="pw",
database='db')
cols = "`,`".join([str(i) for i in df.columns.tolist()])
c = mydb.cursor(buffered=True)
for i,row in df.iterrows():
sql = "INSERT INTO `table` (`" +cols + "`) VALUES (" + "%s,"*(len(row)-1) + "%s)"
c.execute(sql, tuple(row)) # I've also tried (tuple(row,)) with the same result
mydb.commit()
当我运行它时,我得到以下信息:
---------------------------------------------------------------------------
MySQLInterfaceError Traceback (most recent call last)
<ipython-input-195-e2067aefba0c> in <module>
11 sql = "INSERT INTO `bas` (`" +cols + "`) VALUES (" + "%s,"*(len(row)-1) + "%s)"
12 print('row:',tuple(row))
---> 13 c.execute(str(sql), tuple(row))
14
15 # the connection is not autocommitted by default, so we must commit to save our changes
c:\programdata\miniconda3\lib\site-packages\mysql\connector\cursor_cext.py in execute(self, operation, params, multi)
255
256 if params:
--> 257 prepared = self._cnx.prepare_for_mysql(params)
258 if isinstance(prepared, dict):
259 for key, value in prepared.items():
c:\programdata\miniconda3\lib\site-packages\mysql\connector\connection_cext.py in prepare_for_mysql(self, params)
663 ]
664 else:
--> 665 result = self._cmysql.convert_to_mysql(*params)
666 elif isinstance(params, dict):
667 result = {}
MySQLInterfaceError: Python type list cannot be converted
我觉得这有点令人困惑,因为我没有将任何列表插入 c.execute() - 只是一个 str (sql) 和一个 tuple(row)。这不是一个可重现的例子,但如果有人知道我能做些什么来解决这个问题,我将不胜感激。
【问题讨论】:
-
请将错误消息以字符串而不是图像的形式发布,因为使用屏幕阅读器的人将无法阅读图像中的文本。另外,您是否尝试过在执行游标之前添加
print(row):row中的值之一是列表吗? -
是的,你是对的。我的数据框中的一列存储为列表。谢谢!
-
你看过
.to_sql方法吗?它处理将 pandas df 插入 SQL 数据库。 pandas.pydata.org/docs/reference/api/… -
是的,也许这也是一种更快的方法?