我们有一个功能
def update_cfg(self, alert_name, description, owner, cfg_json, permission= '{"org_ids":[""], "dept_ids":[""]}'):
try:
sql = "UPDATE scheduled_tasks SET json = %s, last_updated_date = %s, description = %s, permission = %s WHERE owner = %s AND scheduled_task_name = %s;"
return self.execute_write_sql(sql, [cfg_json, datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
description, permission, owner, alert_name])
except Exception as e:
raise e
'Update_cfg'调用'execute_write_sql'函数
def execute_write_sql(self, sql, values, datasource='localdb'):
try:
self.db_con = self.connect_to_db(datasource)
print('values are'+str(values))
# print('value length is' + len(values))
cursor = self.db_con.cursor()
if len(values) > 0:
cursor.execute(sql, values)
print('1st query is' + str(cursor.query))
cursor.execute()
print('2nd query is' + str(cursor.query))
else:
cursor.execute(sql)
print(sql)
self.db_con.commit()
except Exception as exception:
logging.error("Failed to execute SQL in the function execute_write_sql: " + sql)
print(sql)
self.exception = exception
if self.db_con != None:
self.db_con.rollback()
return False
finally:
if (self.db_con != None):
self.db_con.close()
return True
“ execute_write_sql”函数的“值”输入是一个列表:
['{giant json}', '2019-03-25 14:49:36', 'test', '{"org_ids":["xxx"], "dept_ids":[]}', 'abc', 'v2']
这使得'cursor.query'返回带有不正确的'\'符号的sql查询
UPDATE scheduled_tasks SET json = \'{giant json}\', last_updated_date = \'2019-03-25 14:49:36\', description = \'test\', permission = \'{"org_ids":["xxx"], "dept_ids":[]}\' WHERE owner = \'abc\' AND scheduled_task_name = \'v2\';
理想情况下,我们希望sql查询不包含'\'
UPDATE scheduled_tasks SET json = '{giant json}', last_updated_date = '2019-03-25 14:49:36', description = 'test', permission = '{"org_ids":["xxx"], "dept_ids":[]}' WHERE owner = 'abc' AND scheduled_task_name = 'v2';
有什么简单的方法可以解决此问题吗?
答案 0 :(得分:0)
此链接的启发:
https://www.compose.com/articles/formatted-sql-in-python-with-psycopgs-mogrify/
setContentTypeFromExtension()