这段代码如何pythonic?

 天涯flyer_948 发布于 2022-10-28 07:12

查询数据库所有idlist里的文章,加入article_list.

article_list = []
for i in range(0, len(list)):
    cur.execute('select * from articles where id = {}'.format(list[i]))
    article_list.append(cur.fetchone())

怎么把上面的一句话写成一句python语句呢?

article_list.append(
    cur.execute('select * from articles where id = {}'.format(list[i]))
       for i in range(0, len(list))
                    )

我这么写,但是返回article_list[ at 0x10e112960>].似乎并没有把具体的值append.

2 个回答
  • 我觉得你首先应该SQLic……

    cur.execute('select * from articles where id in ({})'.format(','.join(str(v) for v in list)))

    当然更重要的是不要随便自己拼SQL,SQL注入一点都不好玩,一 点 都 不 好 玩
    而且不要随便用list来当变量名字啊……

    2022-10-29 12:37 回答
  • article_list = [cur.fetchone() for i in list if cur.execute('.....')]

    因为execute返回的是结果数量,所以if后面可以根据需求自行发挥……

    2022-10-29 12:37 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有