用Python将MongoDB数据导入MySQL时对象类型字段如何处理
适配代码方案
首先你需要先在MySQL的example_mysql表中新增needed_techs字段,字段类型设置为JSON即可适配存储MongoDB返回的对象类型数据。
优化后的完整代码如下,同时修复了原代码的SQL注入风险,改用pymysql参数化查询更安全:
import json import pymysql import datetime # 原有字段处理逻辑 location = job_offer.get('location')[0] title_role = job_offer.get('title_role')[0] min_years = job_offer.get('min_years')[0] # 新增needed_techs字段处理,将对象转为JSON字符串 needed_techs = json.dumps(job_offer.get('needed_techs', {})) conn = pymysql.Connect(user='root', database='example', host='localhost', port=3306) cursor = conn.cursor() snapshot_date = datetime.date.today().strftime("%Y-%m-%d") # 改用参数化查询避免SQL注入,同时新增needed_techs字段写入 statement = "insert into example_mysql (location, snapshot_date, title_role, min_years, needed_techs) values (%s, %s, %s, %s, %s);" cursor.execute(statement, (location, snapshot_date, title_role, min_years, needed_techs)) # 提交事务 conn.commit() # 关闭连接 cursor.close() conn.close()
补充说明
- 如果你后续需要对
needed_techs里的字段做单独查询筛选,也可以把对象里的每个键单独拆成MySQL的字段,读取的时候逐个取job_offer['needed_techs'].get('键名')写入对应字段即可。 - 原代码的f字符串拼接SQL存在严重的SQL注入风险,参数化查询是更安全的实现方式,也能自动处理特殊字符转义,不需要手动处理单引号等问题。
内容的提问来源于stack exchange,提问作者Marquez Yannick
相关产品推荐
相关产品推荐

