Creating objects in thread created with subclass

Jeff Shannon jeff at ccvcorp.com
Wed Apr 10 16:06:41 EDT 2002


In article <mailman.1018401560.15646.python-list at python.org>, 
narnett at mccmedia.com says...
> > From: python-list-admin at python.org
> > [mailto:python-list-admin at python.org]On Behalf Of Jeff Shannon
> 
> ...
> 
> > No, that is definitely *not* the right way to do it -- as I keep
> > saying, exec/eval() are very rarely the right way to do it,
> > whatever "it" may be.  ;)
> 
> Ah.  Well.  Then as long as we're on the subject... I couldn't figure out a
> way to build an insert command for MySQLdb without it.  Given a list of
> tuples to insert, I need to give the database handle a statement that looks
> like this:
> 
> self.dbh.execute("INSERT INTO Foo (fieldnames) VALUES (%s,[%s])",(data[1:]))
> 
> The first tuple in the list of tuples is the fieldnames, which can vary.
> Thus, the number of "%s" occurrences in the statement has to be calculated.
> Is there a way to create this insertion statement without using exec?

Okay, first I should warn you that I don't know SQL and haven't 
used any DB modules yet, but...  you need to dynamically *create* 
the string that you pass to execute, but that doesn't necessarily 
mean that you need to dynamically execute that string, if you get 
the difference. ;)

Try something like this:

mystring = "INSERT INTO Foo (fieldnames) VALUES (%s"
mystring +=  ",%s" * (len(data)-2) + ")"
self.dbh.execute(mystring, (data[1:]))

(Note that I'm subtracting 2 from the length of data -- one for 
the fieldnames tuple that you're excluding with your slice, and 
one for the initial '%s' which does not want a comma before it.)

There's probably plenty of ways to clean this up (and speed it 
up, too), and I won't place any bets on whether this is exactly 
the format you need the string to be in, but this general 
approach should work.

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list