Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #46362
| References | <2fd0cae6-6cfe-4163-964e-2aa863e65f5e@googlegroups.com> |
|---|---|
| Date | 2013-05-29 11:02 +0100 |
| Subject | Re: MySQL dymanic query in Python |
| From | Fábio Santos <fabiosantosart@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2345.1369821775.3114.python-list@python.org> (permalink) |
[Multipart message — attachments visible in raw view] - view raw
On 29 May 2013 10:13, "RAHUL RAJ" <omrahulrajcse@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.
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
MySQL dymanic query in Python RAHUL RAJ <omrahulrajcse@gmail.com> - 2013-05-29 02:09 -0700
Re: MySQL dymanic query in Python Fábio Santos <fabiosantosart@gmail.com> - 2013-05-29 11:02 +0100
Re: MySQL dymanic query in Python RAHUL RAJ <omrahulrajcse@gmail.com> - 2013-05-30 05:22 -0700
csiph-web