python - 如何使用变量将python中的数据插入mysql数据库?
问题描述
将数据插入查询时,如何直接使用变量代替字符串?
import pymysql
import json
# Connect to the database
conn = pymysql.connect(host='localhost',
user='test',
password='br',
db='testing')
cur = conn.cursor()
json_data = json.loads(open("res.json").read())
# currently this is the query I want to execute
query = """INSERT INTO RF.candidate (
first_name, last_name, phone, email,
social, website
) VALUES (
'David', 'N', '["+1 917 547 7813", "+1 917 547 7823"]',
'["testing@gmail.com"]', '["fb.com/rtr"]', '["google.com", "sris.com"]',
'{"Degree": {"MBA": {"Majors": [""]}}}',
);"""
cur.execute(query)
# datatypes:
# first_name : varchar
# last_name : varchar
# phone : json
# email : json
# social : json
# website: json
# education: json
电子邮件地址数据是json_data
可变的,
print(json_data['email'])
# returns
["testing@gmail.com"]
email_array = json.dumps(json_data['email'])
现在我想email_array
在 sql 查询email
列中传递变量,而不是像上面那样在查询变量中手动写入 json 列表?
我怎样才能在python中做到这一点?
解决方案
query = """INSERT INTO RF.candidate (
first_name, last_name, phone, email,
social, website
) VALUES (
'David', 'N', '["+1 917 547 7813", "+1 917 547 7823"]',
'[{}]', '["fb.com/rtr"]', '["google.com", "sris.com"]'
);""".format(EMAIL_VARIABLE)
如果电子邮件变量是一个数组,则使用{}
其他方式[{}]
推荐阅读
- javascript - Jquery 为游戏中的 div 角色设置动画
- javascript - CytoscapeJS in React: run the layout
- python - 如何使用相应的字典值自动填充可选函数参数?
- python - 为什么我的爬虫只在csv文件中写错了部分数据?
- sql - 如何在 SQL 中满足条件之前对行求和
- r - R:用上面的值填充一组列中的所有 NA
- swift - 如何删除与不存在的变量相关的控制台错误
- python - Matplotlib 极坐标绘图:以度数显示极坐标刻度,采用十进制格式
- python - 增加 Tkinter Notebook 中选项卡按钮的大小
- javascript - 谷歌浏览器不接受分页符