【问题标题】:How to use wild card % in python string for sql statement如何在python字符串中为sql语句使用通配符%
【发布时间】:2018-10-11 05:01:48
【问题描述】:

我遇到这种情况是要检查数据库中的一行中是否存在帐号。该列可以包含多个帐号,每个帐号以逗号分隔,例如。 00001,00002,00003。 例如案例:SELECT * FROM finance_collection.member WHERE account_ids LIKE 00001,% OR %,00001 OR %,00001,% OR 00001 为此,我编写了一条 SQL 语句:

account_exists = " SELECT * FROM finance_collection.member WHERE account_ids LIKE %s,% OR %,%s OR %,%s,% OR %s "  

这里 %s 是传入的帐号,是一个逗号,% 是一个多字符通配符。

    try:
    with connection.cursor() as cursor:

        sql = sqls.account_exists
        cursor.execute(sql, (account, account, account, account))
        return True

    except pymysql.Error as error:
    print(error)
    return False

我正在使用 pymysql 进行连接,但查询似乎不起作用。我尝试了各种组合,例如将%s,%' ' 和其他组合在一起,但它们都不起作用。你能在这里给我点灯吗?

【问题讨论】:

  • “查询不工作。”你可以说得更详细点吗?错误?错误的结果?什么?删除 try/except 以找出整个回溯。
  • 你试过转义 '\' % 字符吗?
  • 您是否尝试直接在数据库中运行此查询? ;)
  • 加倍% 以逃避它们。
  • @AndrewPaxson 那行不通。它会提高TypeError: not enough arguments for format string

标签: python sql python-3.x pymysql


【解决方案1】:

用另一个 % 转义 %(是的,这没有多大意义,但就是这样):

x = "a=%sx%%2C" % ('text')
x
>>> 'a=textx%2C'

【讨论】:

    猜你喜欢
    • 2011-12-22
    • 1970-01-01
    • 2011-11-07
    • 2015-02-28
    • 2020-12-06
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2012-12-21
    相关资源
    最近更新 更多