MySQLdb question... using table name as arg

Sean Berry sean at buildingonline.com
Fri Feb 3 13:54:20 EST 2006


"Carsten Haese" <carsten at uniqsys.com> wrote in message 
news:mailman.1392.1138992081.27775.python-list at python.org...
> On Fri, 2006-02-03 at 13:24, Sean Berry 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.
>
> As you have discovered, the table name is not allowed to be a parameter.
> You have to build the query string for the appropriate table, then hand
> it to execute for filling in the actual parameters:
>
> queryString = "update "+tableName+" set col1=%s, col2=%s,..."
> c.execute(queryString, (val1, val2,...))
>
> HTH,

Thanks... that is kind of what I figured.







More information about the Python-list mailing list