优化以下python中三个mysql查询语句,得到三个独立的结果 sql = '''select id,name_work,date_z,isDelete,biaozhun from dubanworks where id_person='{0}' order by isDelete desc,id desc '''.format(id_person) co.to_sql(sql) jg1 = cs.fetchall() sql = '''select id,name_work,date_z,isDelete,biaozhun from dubanworks where id_fenguan like '#{0}#' order by isDelete desc,id desc '''.format(id_person) co.to_sql(sql) jg2 = cs.fetchall() sql = '''select id,name_work,date_z,isDelete,biaozhun from dubanworks where id_weijieshuo='#{0}#' order by isDelete desc,id desc '''.format(id_person) x = co.to_sql(sql) co.to_sql(sql) jg3 = cs.fetchall() data ={"A":jg1,"B",jg2,"C",jg3}
时间: 2024-03-04 18:48:40 浏览: 52
优化后的代码如下:
```
sql1 = '''SELECT id, name_work, date_z, isDelete, biaozhun FROM dubanworks WHERE id_person=%s ORDER BY isDelete DESC, id DESC'''
cs.execute(sql1, (id_person,))
jg1 = cs.fetchall()
sql2 = '''SELECT id, name_work, date_z, isDelete, biaozhun FROM dubanworks WHERE id_fenguan LIKE %s ORDER BY isDelete DESC, id DESC'''
cs.execute(sql2, ('#' + id_person + '#',))
jg2 = cs.fetchall()
sql3 = '''SELECT id, name_work, date_z, isDelete, biaozhun FROM dubanworks WHERE id_weijieshuo=%s ORDER BY isDelete DESC, id DESC'''
cs.execute(sql3, ('#' + id_person + '#',))
jg3 = cs.fetchall()
data = {"A": jg1, "B": jg2, "C": jg3}
```
这里使用了参数化查询,避免了SQL注入的风险。同时,将SQL语句拆分为三个独立的查询,使用不同的参数,避免了使用WHERE子句中的OR操作符。此外,使用了更加清晰的命名,使得代码更易读。
阅读全文