我有一个多行字符串(大MySQL查询),我想将它与字典格式(数据)是这样的:蟒蛇 - 多格式字符串%字典
query = """
INSERT LOW_PRIORITY INTO goods(id, type, volume, strength,
country, price, description, year, image, url, class, color,
grape, vintage, dryness, shop, added)
VALUES (
'%(id)s',
'%(type)s',
'%(volume)s',
%(strength)d,
'%(country)s',
%(price)d,
'%(description)s',
'%(year)s',
'%(image)s',
'%(url)s',
'%(class)s',
'%(color)s',
'%(grape)s',
%(vintage)d,
'%(dryness)s',
'%(shop)s',
'%(added)s'
) ON DUPLICATE KEY UPDATE
type = '%(type)s',
volume = '%(volume)s',
strength = %(strength)d,
country = '%(country)s',
price = %(price)d,
description = '%(description)s',
year = '%(year)s',
image = '%(image)s',
url = '%(url)s',
class = '%(class)s',
color = '%(color)s',
grape = '%(grape)s',
vintage = %(vintage)d,
dryness = '%(dryness)s',
shop = '%(shop)s',
added = '%(added)s""" % data
当我试图做到这一点我没有得到任何错误,但我的字符串消失。有什么办法可以解决这个任务吗?
更新: 我发现了这个问题。我试图用我的字典的Unicode值格式化ascii字符串。我没有看到回溯,因为try/except块,我的方法与查询执行已被调用。 道德故事是:总是检查Python 2.x中的字符串编码
你不应该用纯字符串操作来完成这个工作您的输入将无法正确转义。 'MySQLdb'支持[PEP 249](http://www.python.org/dev/peps/pep-0249/),它指定:'cursor.execute(操作,参数)'。 – beerbajay 2012-02-10 12:35:33
看起来很有希望,但我找不到字典的例子。你能指点一下吗? – bbrodriges 2012-02-10 12:55:56
[某些示例](http://mysql-python.sourceforge.net/MySQLdb.html#some-examples),例如'c.execute(“INSERT INTO breakfast(name,spam,eggs,sausage,price)VALUES(%s,%s,%s,%s,%s)”,“垃圾邮件和香肠爱好者的盘子” 1,8,7.95])' – beerbajay 2012-02-10 12:59:42