Re: MySQLdb question... using table name as arg



Carsten Haese wrote:
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 ... 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....
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, ...))

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....
queryString = "update "+tableName+" set col1=%s, col2=%s,..."
c.execute(queryString, (val1, val2,...))


Since you are in control of the query strings, you might try:
choose a string ('<table>' in this example) to represent the table name
that will never appear in your queries to represent the table name,
then do something like:

for table_name in 'first', 'second', 'third', 'fourth':
def perform(query, args):
return cursor.execute(
table_name.join(query.split('<table>')), args)
perform('UPDATE <table> SET col1 = %s, col2 = %s', (val1, val2))
perform('UPDATE <table> SET col4 = %s, col5 = %s', (val4, val5))

Although, frankly, this doesn't sound like a well-designed database.


--Scott David Daniels
scott.daniels@xxxxxxx
.



Relevant Pages

  • Re: Problems with Delete Command
    ... The SQL could get fairly messy if you need to construct it in code, ... ContactID, and WebComID, and create your on-the-fly SQL on that saved query, ... to find the list of ContactIDs from the junction table, ... This is a style/readability thing: if you are going to use string ...
    (microsoft.public.access.tablesdbdesign)
  • Re: Need help with Code Please!!!
    ... the actual string that gets built at the end of the SQ1 build process. ... The message says Syntax error in query expression ... Dim rs As Recordset 'object ref to qryCompany\USFNumber ...
    (microsoft.public.access.formscoding)
  • Re: Need help with Code Please!!!
    ... putting the query SQL itself in here maybe it will help you understand what I ... the actual string that gets built at the end of the SQ1 build process. ... Dim rs As Recordset 'object ref to qryCompany\USFNumber ... Dim qd As QueryDef 'object ref to query item ...
    (microsoft.public.access.formscoding)
  • Re: Need help with Code Please!!!
    ... the actual string that gets built at the end of the SQ1 build process. ... The message says Syntax error in query expression ... Dim rs As Recordset 'object ref to qryCompany\USFNumber ...
    (microsoft.public.access.formscoding)
  • Re: Error using " in .open with ADODB.Recordset
    ... recordset but I'm getting hung up on the SQL statement. ... query that has a string as a condition. ... Dim mrk As String ...
    (microsoft.public.data.ado)