[Tutor] _pg module and the insertion of random numbers...

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 11 Apr 2001 03:14:07 -0700 (PDT)


On Tue, 10 Apr 2001 kromag@nsacom.net wrote:

> I am attempting to insert random numbers into a PostGreSQL database using _pg 
> and random. I am unsure as to syntax when adding variables.
> 
> I have attempted the following:
> 
> import _pg
> import random
> db.connect('test', 'localhost')
> db.query("insert into pork values(`random.randint(1,1000)`+ 'stuff' +'1-2-
> 1999')")

Python doesn't do string interpolation within strings until you actually
trigger it.  That is, as far as Python is concerned, both the single and
double quotes have the same meaning: there's no difference between them,
and no "interpolative context" as in Perl.  What you passed to the query
was probably the literal string:

  insert into pork values(`random.randint(1,1000)`+ 'stuff'+'1-2-1999')


Instead, you'll probably want to use the string interpolation operator
'%'.  There's a brief explanation about it here:

http://python.org/doc/current/tut/node9.html#SECTION009100000000000000000

The main idea is to tell Python to "fill in the blanks" --- wherever it
sees a '%s' within the string, it'll replace it with something useful
when we actually do the interpolation:

    db.query("insert into pork values(%s, stuff, 1-2-1999)" %
             random.randint(1, 1000))


Try some examples from the tutorial, and if it's still a little unclear,
feel free to ask us questions about it.  Good luck!