MySQL dymanic query in Python

Fábio Santos fabiosantosart at gmail.com
Wed May 29 06:02:51 EDT 2013


On 29 May 2013 10:13, "RAHUL RAJ" <omrahulrajcse at gmail.com> wrote:
>
> Can anyone tell me the proper way in which I can execute dynamic MySQL
queries in Python?
>
> I want to do dynamic queries for both CREATE and INSERT statement.
>
> Here is my attempted code:
>
>
> sql="create table %s (%%s, %%s, %%s ... )" % (tablename,''.join(fields)+'
'.join(types))
> cur.execute(sql)
>
>
> where 'field' is the fieldnames stored in a list and 'types' are the
fieldtypes stored in a list.

You need to join the fields and the field types. Use zip().

Then join with commas.

fields_and_types = ['%s %s' % (field, type) for field, type in zip(fields,
types)]

what_goes_between_the_parens = ', '.join(fields_and_types)

sql = 'create table %s (%s)' % (tablename, what_goes_between_the_parens)

See where that gets you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130529/d1c066d6/attachment.html>


More information about the Python-list mailing list