MySQLdb question... using table name as arg

Jim Segrave jes at nl.demon.net
Fri Feb 3 17:59:46 EST 2006


In article <%cNEf.19800$sA3.14913 at fed1read02>,
Sean Berry <sean at buildingonline.com> wrote:
>I have four tables that all have the same column names (50 in each.)
>
>I have created an admin program to edit, delete and add records to the 
>tables and would like to use the table name as a variable in each query so 
>the code can be used for each of the 4 tables.  Usually I would do something 
>like this by having 1 table with special column to categorize the records as 
>I am doing with each table, but this specific application requires that I do 
>it with 4 tables instead.
>
>To ensure that string are quoted properly without any hassle I use the 
>execute function like so assuming c is my cursor object...
>
>c.execute("update tableName set col1 = %s, col2 = %s, col3 = %s, ...", 
>(val1, val2, val3, ...))
>
>But, not I want to do this with a variable tableName.  If I add it to the 
>tuple of parameters in the second arg before val1 and replace tableName with 
>%s, then the tableName will be quoted in the query, causing an error.
>
>What is the best (easiest) way for me to accomplish this?  I know it may be 
>a stupid question but I just can't figure it out.

How about interpolating the table name into the string:

c.execute("update %s set col1 = %%s, col2 = %%s, col3=%%s" % (sometable), \
          ['the', 'cat', 'in the hat'])

Note the need to double the %'s for the parameters to be bound.




-- 
Jim Segrave           (jes at jes-2.demon.nl)




More information about the Python-list mailing list