V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
youthfire
V2EX  ›  Python

求教一条 Python 中使用的 sql 语句

  •  
  •   youthfire · 2022-01-18 20:18:28 +08:00 · 2387 次点击
    这是一个创建于 821 天前的主题,其中的信息可能已经有所发展或是发生改变。
    Python 业余编程爱好者,查了好久都没解决,来请求下帮助

    当以下这样写时没问题
    condi1 = 'code like' + '"%' + str(code) + '%"'
    condi2 = 'code like' + '"%' + str(code2) + '%"'
    df = pd.DataFrame(pd.read_sql('select * from f63 where ' + condi1 + ' OR ' + condi2, conn))

    但我想写成 code = 就会报错
    condi1 = 'code =' + '"%' + str(code) + '%"'
    condi2 = 'code =' + '"%' + str(code2) + '%"'
    df = pd.DataFrame(pd.read_sql('select * from f63 where ' + condi1 + ' OR ' + condi2, conn))

    请问是不是“=”转义的问题? 如果是,应该怎么表达,有查到用\,也有用",甚至和 Python 里的 r'有点概念混一起分不清了
    第 1 条附言  ·  2022-01-18 23:06:21 +08:00
    解决了

    df = pd.DataFrame(pd.read_sql("select * from f63 where code = ? OR code = ? AND engine like ?", conn, params=[str(code), str(code2), '%' + str(keystring2) + '%']))
    5 条回复    2022-01-19 10:15:42 +08:00
    ila
        1
    ila  
       2022-01-18 20:22:45 +08:00 via Android   ❤️ 1
    用 f format,
    f"{condi1}"。
    先 print 出来看组装后的字符串
    youthfire
        2
    youthfire  
    OP
       2022-01-18 22:24:58 +08:00
    自己发现了两处问题
    1.改用 code = 时,后面%就不需要了,因为只有在 like 时有效
    2.安全角度和便捷角度,应该使用参数写法

    但换了种表达方式,似乎也不见效

    df = pd.DataFrame(pd.read_sql("select * from f63 where code = ? OR code = ? AND engine like '%?%'", (str(code), str(code2), str(keystring2))), conn)
    youthfire
        3
    youthfire  
    OP
       2022-01-18 23:05:58 +08:00
    解决了

    df = pd.DataFrame(pd.read_sql("select * from f63 where code = ? OR code = ? AND engine like ?", conn, params=[str(code), str(code2), '%' + str(keystring2) + '%']))
    dayeye2006199
        4
    dayeye2006199  
       2022-01-19 01:43:47 +08:00   ❤️ 1
    虽然这边是用在 pandas 里面,但是拼装 sql 语句不是好习惯。
    RRRoger
        5
    RRRoger  
       2022-01-19 10:15:42 +08:00   ❤️ 1
    用 py3 的 f"....." 或者 "...".format()

    都比你这个+清晰
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5143 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 09:30 · PVG 17:30 · LAX 02:30 · JFK 05:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.