Python3 if 变量variable SQL where 语句拼接

最近在写python3的项目,在实际中运用到了根据 if 判断变量variable ,然后去拼接where子句。但是在百度、BING搜索中未找到合适的答案,这是自己想出来的典型php写法,这里做一下记录。不知道在python中如何做,如有python大神知道,请指点一下。

def getRooms( excludeId = None , limit = None ):
    sql = 'SELECT * from computer_room WHERE 1=1 '
    param = []
    if excludeId :
        sql += 'AND id <> %s '
        param += [excludeId]
    sql += 'ORDER BY weights ASC , id DESC '
    if limit :
        sql += 'LIMIT %s '
        param += [limit]
    config.cursor.execute( sql , param )
    return config.cursor.fetchall()

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注