[英]ProgrammingError while trying to insert data into a MySQL table using Python
[英]Insert pandas DataFrame() into an MySQL table raises ProgrammingError
給定一個 dataframe ( df
),其中 1 列的所有行都包含一個列表,基本上相應的列可以看作是列表的列表。 列的 rest 是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
注意:
hobbies
欄的格式為text utf8_general_ci
參考資料:
嘗試將其全部轉換為常規字符串。 只需在您的姓名列上應用 lambda function 即可。 例如:
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
字符串絕對可以與 sql 配合使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.