【问题标题】:Use placeholder to delete rows code in mysql with python mysqldb使用占位符使用 python mysqldb 删除 mysql 中的行代码
【发布时间】:2012-09-23 03:55:39
【问题描述】:
conn = MySQLdb.connect(hostip, username, password, dbname)
cur = conn.cursor()
tablename = raw_input("Choose your table name: ")
if tablename:
cur.execute("SELECT * FROM %s" % tablename)
rows = cur.fetchall()

desc = cur.description
fields = [j[0] for j in desc]

for row in rows:
    for kword in dust:
        for fs in fields:
            cur.execute("SELECT * FROM %s WHERE %s LIKE '%%s%'" % (tablename, fs, kword))

conn.close()
#

像简单的代码一样,我想在 mysqldb 中传递参数 use %% PlaceHolder,但它不起作用,有人能帮我解释一下那句话吗? '%%s%' ,第一个和最后一个 '%' 是使用 'like' 的 sql 语法 非常感谢!

【问题讨论】:

    标签: python mysql-python


    【解决方案1】:

    使用 %s 和 {} 格式化字符串有两种方式,示例如下:

    print "key:%(key)s value:%(value)s" % {"key":"key1","value":"value1"}
    print "{{keep me}} key:{key} value:{value}".format(**{"key":"key1","value":"value1"})
    

    解决您的问题:

    >>> "SELECT * FROM {tablename} WHERE {field} LIKE '%{keyword}%'".format(**{"tablename":"UserTable","field":"NameField","keyword":"Wuliang"})
    "SELECT * FROM UserTable WHERE NameField LIKE '%Wuliang%'"
    

    【讨论】:

      猜你喜欢
      • 2015-07-08
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2018-05-11
      • 2021-03-26
      • 2020-12-15
      相关资源
      最近更新 更多