Building strings (was Re: Creating objects in thread created with subclass)

Aahz aahz at pythoncraft.com
Wed Apr 10 19:22:17 EDT 2002


In article <mailman.1018401560.15646.python-list at python.org>,
Nick Arnett <narnett at mccmedia.com> wrote:
>
>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?

fields = []
values = []
for name, value in data:
    fields.append(name)
    values.append("'" + SQLescape(value) + "'")

fields = string.join(',', fields)
values = string.join(',', values)
statement = "INSERT INTO Foo (%s) VALUES (%s)" % (fields, values)

Never underestimate the power of a for loop combined with lists.

(This should be a Cookbook recipe, but the site's down right now.)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"Playing rules lawyer on UseNet is like watching Captain Hook wanking."
--Brian Mailman, news.groups



More information about the Python-list mailing list