dictonary

Max M maxm at mxm.dk
Wed Mar 13 19:33:52 EST 2002


Bernard Yue wrote:

>
>Max M wrote:
>
>>A bit more readable perhaps?
>>
>>keys = dict.keys()
>>vals = dict.vals()
>>sql = "insert into table(%s) values (%s)" % (
>>     ','.join(keys),
>>     ','.join(list(len(keys)*'?'))
>>)
>>cursor.execute(sql, vals)
>>
>
>Will this method cause problem when inserting numbers (strings are
>quoted, but not for numbers)?  I remember it will (not 100% sure, it's
>been a while).  Thats what I've done (with MySQLdb):
>

If it follows the Python DB standard, quoting should not be nessecary 
when doing it like above. The execute method should automatically do the 
correct quoting whenever nessecary. To quote the spec:

------------------------------
"
 The module will use the __getitem__ method of the parameters object to 
map either positions (integers) or names (strings) to parameter values. 
This allows for both sequences and mappings to be used as input.

The term "bound" refers to the process of binding an input value to a 
database execution buffer. In practical terms, this means that the input 
value is directly used as a value in the operation. The client should 
not be required to "escape" the value so that it can be used -- the 
value should be equal to the actual database value.
"
------------------------------

So the above code generates a query like:

sql = "insert into table(firstname, lastname, country) values (?,?,?)"

The questionmarks are placeholders for the values in the parameter tuple 
passed to execute.

cursor.execute(sql, ("Max's", 'M', 'Denmark'))

You could also chose other ways to format your querystrings.

regards Max M

------------------------------
paramstyle: String constant stating the type of parameter marker 
formatting expected by the interface. Possible values are [2]:

    'qmark' = Question mark style, e.g. '...WHERE name=?'
    'numeric' = Numeric, positional style, e.g. '...WHERE name=:1'
    'named' = Named style, e.g. '...WHERE name=:name'
    'format' = ANSI C printf format codes, e.g. '...WHERE name=%s'
    'pyformat' = Python extended format codes, e.g. '...WHERE name=%(name)s'
------------------------------




More information about the Python-list mailing list