我的目标是在Python中动态生成类似于
的SQL查询UPDATE SURV_SCF_ID_STATUS
SET AGE_STATUS = CASE NAME
WHEN 'entityXp1' THEN '1'
WHEN 'entityXp3' THEN '0'
WHEN 'entityXpto1' THEN '1'
WHEN 'entityXpto3' THEN '1'
END
WHERE NAME IN ('entityXp1', 'entityXp3', 'entityXpto1', 'entityXpto3')
这是我到目前为止所拥有的, 但仍然感觉像一个丑陋的黑客,
logs_age_list = [['entityXp1', '1'], ['entityXp3', '0'], ['entityXp1', '1'], ['entityXpto3', '1']]
conditions_list = []
where_list = []
for entity, status in logs_age_list:
conditions_list.append("\t\tWHEN %(entity)s THEN %(value)s" % locals() )
where_list.append(entity)
conditions_string = '\n'.join(conditions_list)
where_string = ', '.join(where_list)
sql = '''
UPDATE SURV_SCF_ID_STATUS
SET AGE_STATUS = CASE NAME
%(conditions_string)s
END
WHERE NAME IN (%(where_string)s)
''' % locals()
print sql
有更明显的方法吗? 我没有找到任何允许这个的Python模块。
由于
答案 0 :(得分:1)
您可以通过
构建condition_stringconditions_string = ' '.join(["\t\tWHEN %s THEN %s\n" % (x, y) for x, y in logs_age_list])
和where_string为
where_string = ', '.join([duo[0] for duo inlogs_age_list])
然后执行类似
的操作sql = '''
UPDATE SURV_SCF_ID_STATUS
SET AGE_STATUS = CASE NAME
%s
END
WHERE NAME IN (%s)
''' % (conditions_string, where_string)
但是通常你应该尝试使用DB模块的execute方法来避免SQL注入。
以下是http://docs.python.org/library/sqlite3.html
的示例# Never do this -- insecure!
symbol = 'IBM'
c.execute("... where symbol = '%s'" % symbol)
# Do this instead
t = (symbol,)
c.execute('select * from stocks where symbol=?', t)