2012-02-10 139 views
1

我有一个多行字符串(大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中的字符串编码

+0

你不应该用纯字符串操作来完成这个工作您的输入将无法正确转义。 'MySQLdb'支持[PEP 249](http://www.python.org/dev/peps/pep-0249/),它指定:'cursor.execute(操作,参数)'。 – beerbajay 2012-02-10 12:35:33

+0

看起来很有希望,但我找不到字典的例子。你能指点一下吗? – bbrodriges 2012-02-10 12:55:56

+0

[某些示例](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

回答

0

你是什么意思与“消失”?如果您发出print query,返回什么? 看起来你错过了最后一行的单引号:不应该是added = '%(added)s'""" % data

+0

感谢您的错误报价。通过“消失”我的意思是,如果我将删除%数据并调用“打印查询”,它将被成功打印,但%数据查询根本不打印 – bbrodriges 2012-02-10 12:27:17

0

我怀疑你的数据字典缺少一些关键字。

例如:

In [1]: "%(xx)s" % dict() 
--------------------------------------------------------------------------- 
KeyError         Traceback (most recent call last) 
/<redacted>/<ipython-input-1-475612d1eaa2> in <module>() 
----> 1 "%(xx)s" % dict() 

KeyError: 'xx'