【发布时间】:2021-06-27 23:22:15
【问题描述】:
给定一个数据框 (df),其中 1 列的所有行都包含一个列表,基本上相应的列可以看作是一个列表列表。其余列是str、int 或bool。第一行 (df.iloc[0]) 打印以下内容:
name John
isMale True
age 30
hobbies ['hiking', 'gaming', 'reading', …
Name: 0, dtype: object
这是我的代码:
engine = create_engine('mysql+mysqlconnector://{user}:{password}@{host}:{port}/{database}'.format(**config))
df.to_sql(name='test', con=engine, if_exists='append', index=True)
上面执行:
[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) ... ]}]
我想将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
- 有没有办法将 python 列表作为单元格值插入?
- 如何将 python 列表转换为有效的 MySQL 类型?
注意:
-
hobbies列的格式为text utf8_general_ci
参考文献:
【问题讨论】:
标签: python mysql pandas dataframe sqlalchemy