def escape(value): """ Converts a string to a quoted string and a number to a decimal expression string. Result of the function can be used directly as a right-hand-side expression in queries. Lists and tuples are converted to python tuples with each element escaped. """ return MySQLdb.escape(value, MySQLdb.converters.conversions)
def escape(self, string): """ Escapes a string for use in a query This is the equivilate and MySQLdb.escape() @author: Nick Verbeck @since: 9/7/2008 """ return MySQLdb.escape(string)
def insert_many(self, table, fields, mapping, objects, do_update=True): """ INSERT INTO table (fields) VALUES (mapping(objects)). Arguments: table: table name. fields: name of columns. mapping: typically a lambda that takes an element in the objects list and return a tuple corresponding to a row to insert. objects: list of objects to insert. """ if len(objects) == 0: return sqlbase = 'INSERT INTO `{table}` ({fields}) VALUES %s'.format( table=table, fields=','.join(['`%s`' % f for f in fields])) if do_update: sqlbase += ' ON DUPLICATE KEY UPDATE ' + ','.join( ['`{f}`=VALUES(`{f}`)'.format(f=f) for f in fields]) template = '(' + ','.join(['%s'] * len(fields)) + ')' # template = (%s, %s, ...) values = '' for obj in objects: if mapping is None: values += template % MySQLdb.escape( obj, MySQLdb.converters.conversions) else: values += template % MySQLdb.escape( mapping(obj), MySQLdb.converters.conversions) # MySQL allows queries up to 1M characters if len(values) > config.mysql.max_query_len or obj == objects[-1]: if logger.getEffectiveLevel() == logging.DEBUG: logger.debug(sqlbase % values) self.query(sqlbase % values) values = '' else: values += ','
def esc(self, s): if isinstance(s, unicode): s = s.encode("utf8") try: return self.db.escape(s) except: try: return MySQLdb.escape(s, self.db.converter) except: # TODO: this should not be necessary. # maybe switch to # cursor.execute("select whatever from whomever where something = %s", my_parameter) #? s = str(s) return "'" + s.replace('\\', '\\\\').replace('"', '\\"').replace('\'', '\\\'') + "'"
def escape_parameter(self, parameter): if isinstance(parameter, str): return MySQLdb.escape_string(parameter) else: return MySQLdb.escape(parameter)
def literal(o): return MySQLdb.escape(o, MySQLdb.converters.conversions)