sql - Python manual query building: how to escape strings for MySQL in list comprehension where clause builder? -
i'm using django site, can't use django's orm because it's not built "n" databases dynamically selected user joins between multiple databases, otherwise trust me love to.
i'm stuck building query hand , take @ trickery list comprehension:
def buildquery(self, pagedata, num_per_page) : given_fields = {k:v k,v in self.entity.fields.items() if k in pagedata.iterkeys()} where_clauses = [(given_fields[k] % pagedata) k in given_fields if pagedata[k].strip() != ''] if where_clauses: self.queryparts['whereclause'] = 'where ' + ' , '.join(where_clauses) else: self.queryparts['whereclause'] = '' if pagedata.get('sort_by', '1') != '': self.queryparts['sortby'] = 'order %s %s' % (pagedata.get('sort_by','1'), pagedata.get('sort_dir','asc')) else: self.queryparts['sortby'] = '' self.queryparts ['limit'] = 'limit ' + self.buildlimit(pagedata.get('page',1), num_per_page) return self.entity.query % self.queryparts
what above take intersection of fields page , class fields. sample "entity" looks this:
class event: fields = {'keyword': "(rmt.title '%(keyword)s' or rmt.episode_name '%(keyword)s') ", 'service_name': "(s.short_name '%(service_name)s' or rch.aliases '%(service_name)s')", 'puid': "ime.program_unique_id '%(puid)s%%'", 'ims_theme': "", 'content_type': "rmt.types in ('%(content_type)s')", 'genre': "rmt.genres ('%(genre)s')", 'service_uid': "s.service_uid in (%(service_uid)s)"} query = '''select rme.image_path image, rmt.title title, ime.program_unique_id puid, s.short_name service_name, s.service_id sid, ime.begin_time, ime.ims_event_id %(imsdb)s.service s join %(imsdb)s.event ime on ime.service_uid = s.service_uid left join %(rmsdb)s.event rme on ime.eit_id = rme.event_id , rme.service_uid = ime.service_uid left join %(rmsdb)s.text_data rmt on rmt.text_id = rme.text_id left join %(rmsdb)s.channellogo rch on rch.suid = s.service_uid %(whereclause)s %(sortby)s %(limit)s'''
the problem have line:
where_clauses = [(given_fields[k] % pagedata) k in given_fields if pagedata[k].strip() != '']
how escape apostrophes in field?
the databases mysql foreseeable future.
for more completeness on how "used", here's django view looks like:
def index(request): cursor = connection.cursor() q = querybuilder(entity=querybuilder.event, rmsdb=sources.getcurrentrmsdb(request), imsdb=sources.getcurrentimsdb(request)) sql = q.buildquery(request.get, num_per_page) return httpresponse(sql) cursor.execute(sql) return render(request, 'rma/event.html', {'results' : dictfetchall(cursor)})
well, problem known enough , solution specified in pep249: connector module's paramstyle
defines how pass strings without need manual escape. in usual mysql driver, paramstyle
= "qmark"
, understands pyformat
style.
also can format these string constants manually, but, due sql specifics, dbms dependable.
Comments
Post a Comment