import json
import pymysql.cursors
from pymysql.converters import escape_string
# 连接数据库
db = pymysql.Connect(
host='',
port=3306,
user='',
passwd='',
db='',
charset='utf8'
)
# 获取游标
cursor = db.cursor()
sql = "SELECT * FROM db.test_platform_task where task_name='sixth_form' and mission_id between 79 and 1592 and task_is_auto=0 and task_form !='{}';"
# sql = "SELECT * FROM db.test_platform_task where task_name='sixth_form' and mission_id=88;"
# 使用 execute() 方法执行 SQL 查询
cursor.execute(sql)
# 使用 fetchone() 方法获取单条数据.
# data = cursor.fetchone()
results = cursor.fetchall()
for row in results:
task_form = row[3]
mission_id = row[6]
d_task_form = json.loads(task_form)
keys = d_task_form.keys()
add_d = {
'test1': '测试1', 'test2': '测试2', 'test3': '测试3'
}
if 'test10' not in keys:
d_task_form.update(add_d)
add_str = json.dumps(d_task_form)
update_sql = 'UPDATE `db`.`test_platform_task` SET `task_form`=\'' + escape_string(add_str) + '\' WHERE `mission_id`=' + str(mission_id) + ';'
try:
# 执行SQL语句
cursor.execute(update_sql)
cursor.execute(update_sql2)
# 提交到数据库执行
db.commit()
except Exception as e:
# 发生错误时回滚
print(str(mission_id) + str(e))
db.rollback()
# break
# 关闭数据库连接
db.close()