mysql - 将字典键映射到 Mysql 数据库表列

标签 mysql pandas

我需要帮助来弄清楚如何将字典键与我的 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/

相关文章:

java - 如何在插入时使用typeHandler在mybatis中映射枚举类型

mysql - 更改mysql数据类型

python - 在 Pandas 中查找类型为 float 或特定类型的所有数据框列?

python Pandas |仅从列的特定部分查找最大值

python - 删除 Pandas 列中每一行的空格后的字符

php - 在sql中添加新行

php - 查询数据并显示在html表格中

python - 如何拆分具有多个数据的 Pandas 单元格

python - 根据条件将 Pandas DataFrame 列从 String 转换为 Int

MySQL 分区 - 主键和唯一记录的错误