MySQL dymanic query in Python

R

RAHUL RAJ

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.
 
F

Fábio Santos

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.
 
R

RAHUL RAJ

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))



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.

Fantastic! It worked, Thanks :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top