<p dir="ltr"><br>
On 29 May 2013 10:13, "RAHUL RAJ" <<a href="mailto:omrahulrajcse@gmail.com">omrahulrajcse@gmail.com</a>> wrote:<br>
><br>
> Can anyone tell me the proper way in which I can execute dynamic MySQL queries in Python?<br>
><br>
> I want to do dynamic queries for both CREATE and INSERT statement.<br>
><br>
> Here is my attempted code:<br>
><br>
><br>
> sql="create table %s (%%s, %%s, %%s ... )" % (tablename,''.join(fields)+' '.join(types))<br>
> cur.execute(sql)<br>
><br>
><br>
> where 'field' is the fieldnames stored in a list and 'types' are the fieldtypes stored in a list.</p>
<p dir="ltr">You need to join the fields and the field types. Use zip().</p>
<p dir="ltr">Then join with commas.</p>
<p dir="ltr">fields_and_types = ['%s %s' % (field, type) for field, type in zip(fields, types)]</p>
<p dir="ltr">what_goes_between_the_parens = ', '.join(fields_and_types)</p>
<p dir="ltr">sql = 'create table %s (%s)' % (tablename, what_goes_between_the_parens)</p>
<p dir="ltr">See where that gets you.</p>