1

I'm using python 2.7 I'm writing some query in python

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

I want to format the string in two step something like :

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

The example i wrote is not working. python throws KeyError is there any other option to perform those tasks?

1
  • 6
    That's not how you do databases in Python. Commented Feb 26, 2012 at 17:55

2 Answers 2

7

Use a proper database API.

That said, if you know which keys will be omitted in the first pass, you can do:

>>> "%(a)s and %%(b)s" % {'a': 1}
'1 and %(b)s'
>>> _ % {'b': 2}
'1 and 2'
Sign up to request clarification or add additional context in comments.

1 Comment

This trick is cool. I'm using the Database API for most of the variables. i'm using it with sense, but thanks for the advice
4

Thanks for your answer @katrielalex. I've been trying to do something similar using the string .format() method (python2.6+). Your answer guided me to come up with the following.

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

I hope it helps all of those who want to use the new functionality.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.