能否将Python操作MySQL的if-else语句简化为单if(cond1或cond2)语句?
简化MySQL操作代码中的if-else语句
完全可以把这段代码里的if-else简化成单个if语句,核心是把两个触发插入操作的条件合并:
- 条件1:查询无记录(
not myresult2) - 条件2:查询到的最新state与
newstate不相等(myresult2[0][0] != newstate)
只要满足其中任意一个条件就执行插入,直接用or将两个条件合并到同一个if判断中即可。
简化后的代码
sql1 = "SELECT state FROM YO WHERE function = '%s' ORDER BY time DESC LIMIT 1" % (func) if not myresult2 or myresult2[0][0] != newstate: print("doing insert %s - %s - %s" % (func, newstate, time)) cursor.execute(sql2) db.commit()
额外提示
你当前用%拼接SQL语句存在SQL注入风险,建议改用更安全的参数化查询写法:
sql1 = "SELECT state FROM YO WHERE function = %s ORDER BY time DESC LIMIT 1" cursor.execute(sql1, (func,)) myresult2 = cursor.fetchall()
内容的提问来源于stack exchange,提问作者Sandman112
相关产品推荐
相关产品推荐

