我需要帮助来弄清楚如何将字典键与我的 MySQL 数据库表列映射。
我想在我的 MySQL 数据库表列中插入字典键值,并且我相信在插入值之前我必须先进行正确的键列映射,否则它将失败并且可能会因数据损坏而成功。
非常感谢任何帮助或链接如何操作。
最佳答案
假设您正在使用 SQLAlchemy 引擎与 MySQL 数据库对话,您可以使用 pandas.to_sql 轻松进行插入。
这里是一个示例代码:
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('...') # fill in the connection string
# generate the list of customer dicts
cust1 = {"fname": "john", "lname": "Davis", "custid": 12345, "City": "Houston"}
cust2 = {"fname": "jane", "lname": "Elvis", "custid": 67890, "City": "NewYork"}
customers = [cust1, cust2]
# convert to a DataFrame
df = pd.DataFrame(customers)
# reorder columns so that it is the same as the table
df = df[['fname', 'lname', 'custid', 'City']]
# Do the insert
df.to_sql(table_name, engine, if_exists='append', index=False)
关于mysql - 将字典键映射到 Mysql 数据库表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50856762/