【问题标题】:Insert pandas dataframe into MySQL table - MySQLInterfaceError: Python type list cannot be converted将 pandas 数据框插入 MySQL 表 - MySQLInterfaceError:无法转换 Python 类型列表
【发布时间】: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/…
  • 是的,也许这也是一种更快的方法?

标签: python mysql pandas


【解决方案1】:

也许我可以帮你。 据我所知

MySQLInterfaceError: Python type list cannot be converted

表示您未能将列表转换为字符串... 我建议切换到pymysql 库!它非常易于使用,我对此非常满意。在那里你可以很容易地附加变量或数据帧。

对于名为“df”的数据框:

sql = """INSERT INTO dummy_table(dummy1, dummy2, dummy3) VALUES(%s,%s,%s)"""
for row in df.values.tolist():
    curs.execute(sql, tuple(row))
conn.commit()
conn.close()

对于要附加的单个变量(value1 等),您只需创建一个元组:

sql = """INSERT INTO dummy_table(dummy1, dummy2, dummy3) VALUES(%s,%s,%s)"""
data = (value1, value2, value3)
curs.execute(sql, data)
conn.commit()
conn.close()

请注意,您当然必须在尝试插入之前创建一个表;)还有 dummy1 等是您在创建表时指定的表列的名称。

【讨论】:

    猜你喜欢
    • 2020-07-23
    • 2021-12-02
    • 2021-09-27
    • 2021-03-22
    • 2016-11-14
    • 2018-03-27
    • 2022-06-16
    • 2017-06-22
    • 2018-07-08
    相关资源
    最近更新 更多