2012-02-26 59 views
1

我使用python 2.7 我用Python写一些查询格式化部分

q = ''' 
select * from users where user_name = %(user_name)s and user_email = %(user_email)s 
''' 

我想格式化字符串中的两步 类似:

q2 = q % {'user_name':'david'} 
q3 = q2 % {'user_email':'[email protected]'} 

我写的例子不起作用。 python抛出KeyError 是否有任何其他选项来执行这些任务?

+6

这不是你如何在Python中做数据库。 – 2012-02-26 17:55:49

回答

7

使用适当的数据库API。

这就是说,如果你知道哪些键会在第一遍被省略,你可以这样做:

>>> "%(a)s and %%(b)s" % {'a': 1} 
'1 and %(b)s' 
>>> _ % {'b': 2} 
'1 and 2' 
+0

这个技巧很酷。我为大多数变量使用数据库API。我用它有意义,但感谢您的建议 – user1087310 2012-02-26 18:39:43

3

谢谢您的回答@katrielalex。我一直在尝试使用字符串.format()方法(python2.6 +)来做类似的事情。你的回答引导我拿出以下内容。

>>> s="{a} and {{b}}" 
'{a} and {{b}}' 
>>> s.format(a = 1) 
'1 and {b}' 
>>> _.format(b = 2) 
'1 and 2' 

我希望它可以帮助所有那些谁想要使用的新功能。