简体   繁体   English

将 pandas DataFrame() 插入 MySQL 表会引发 ProgrammingError

[英]Insert pandas DataFrame() into an MySQL table raises ProgrammingError

Given a dataframe ( df ) in which all rows of 1 column contains a list basically the respective column can be seen as a list of lists.给定一个 dataframe ( df ),其中 1 列的所有行都包含一个列表,基本上相应的列可以看作是列表的列表。 The rest of the columns are str , int or bool .列的 rest 是strintbool The first row ( df.iloc[0] ) print the below:第一行( df.iloc[0] )打印以下内容:

name                                  John
isMale                                True
age                                     30
hobbies  ['hiking', 'gaming', 'reading', …
Name: 0, dtype: object

This is my code:这是我的代码:

engine = create_engine('mysql+mysqlconnector://{user}:{password}@{host}:{port}/{database}'.format(**config))
df.to_sql(name='test', con=engine, if_exists='append', index=True)

The above executes:上面执行:

[SQL: INSERT INTO test(`name`, `isMale`, age, hobbies) VALUES (%(name)s, %(isMale)s, %(age)s, %(hobbies)s)]
[parameters: {'index': 0, 'name': 'John', 'isMale': 1, 'age': 50, 'hobbies': ['hiking', 'gaming', 'reading', ... (84 characters truncated) ...  ]}]

I want to insert the df into a mysql table but sqlalchemy raises the following exception:我想将df插入 mysql 表中,但 sqlalchemy 引发以下异常:

Traceback (most recent call last):
        return getattr(self, "_{0}_to_mysql".format(type_name))(value)
    AttributeError: 'MySQLConverter' object has no attribute '_list_to_mysql'

The above exception was the direct cause of the following exception:
    sqlalchemy.exc.ProgrammingError: (mysql.connector.errors.ProgrammingError) Failed processing pyformat-parameters; Python 'list' cannot be converted to a MySQL type

  • Is there a way to insert a python list as a cell value?有没有办法将 python 列表作为单元格值插入?
  • How can I convert a python list to a valid MySQL type?如何将 python 列表转换为有效的 MySQL 类型?

NB :注意

  • The column hobbies is formatted as text utf8_general_ci hobbies栏的格式为text utf8_general_ci

References :参考资料

Try converting it all to regular strings.尝试将其全部转换为常规字符串。 Just apply a lambda function on your name column.只需在您的姓名列上应用 lambda function 即可。 For example:例如:

df = pd.DataFrame({'a':[1,2,3,4], 'b':[['a', 'b','v'], ['s', 'e','r'], ['a', 'j','k'], ['f','g','d']]})

df.b.apply(lambda x: ", ".join(x))
Out[31]: 
0    a, b, v
1    s, e, r
2    a, j, k
3    f, g, d
Name: b, dtype: object

Strings should definitely work fine with sql.字符串绝对可以与 sql 配合使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM