0
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 语法 非常感谢!

4

1 回答 1

0

使用 %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%'"
于 2012-09-23T04:17:06.230 回答