def execute(self, operation, params=None, multi=False): """Executes the given operation Executes the given operation substituting any markers with the given parameters. For example, getting all rows where id is 5: cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,)) The multi argument should be set to True when executing multiple statements in one operation. If not set and multiple results are found, an InterfaceError will be raised. If warnings where generated, and connection.get_warnings is True, then self._warnings will be a list containing these warnings. Returns an iterator when multi is True, otherwise None. """ if not operation: return if self._have_unread_result(): raise errors.InternalError("Unread result found.") self._reset_result() stmt = '' try: if isinstance(operation, unicode): operation = operation.encode(self._connection.charset) except (UnicodeDecodeError, UnicodeEncodeError) as e: raise errors.ProgrammingError(str(e)) if params is not None: try: stmt = operation % self._process_params(params) except TypeError: raise errors.ProgrammingError( "Wrong number of arguments during string formatting") else: stmt = operation if multi: self._executed = stmt self._executed_list = [] return self._execute_iter(self._connection.cmd_query_iter(stmt)) else: self._executed = stmt try: self._handle_result(self._connection.cmd_query(stmt)) except errors.InterfaceError as err: if self._connection._have_next_result: raise errors.InterfaceError( "Use multi=True when executing multiple statements") raise return None
def _process_params(self, params): """ Process the parameters which were given when self.execute() was called. It does following using the MySQLConnection converter: * Convert Python types to MySQL types * Escapes characters required for MySQL. * Quote values when needed. Returns a list. """ if isinstance(params,dict): return self._process_params_dict(params) try: res = params to_mysql = self.db().converter.to_mysql escape = self.db().converter.escape quote = self.db().converter.quote res = map(to_mysql,res) res = map(escape,res) res = map(quote,res) except StandardError, e: raise errors.ProgrammingError( "Failed processing format-parameters; %s" % e)
def set_client_flags(self, flags): """Set the client flags The flags-argument can be either an int or a list (or tuple) of ClientFlag-values. If it is an integer, it will set client_flags to flags as is. If flags is a list (or tuple), each flag will be set or unset when it's negative. set_client_flags([ClientFlag.FOUND_ROWS,-ClientFlag.LONG_FLAG]) Raises ProgrammingError when the flags argument is not a set or an integer bigger than 0. Returns self._client_flags """ if isinstance(flags, int) and flags > 0: self._client_flags = flags elif isinstance(flags, (tuple, list)): for flag in flags: if flag < 0: self._client_flags &= ~abs(flag) else: self._client_flags |= flag else: raise errors.ProgrammingError( "set_client_flags expect int (>0) or set") return self._client_flags
def execute(self, operation, params=None, multi=False): """Executes the given operation Executes the given operation substituting any markers with the given parameters. For example, getting all rows where id is 5: cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,)) The multi argument should be set to True when executing multiple statements in one operation. If not set and multiple results are found, an InterfaceError will be raised. If warnings where generated, and connection.get_warnings is True, then self._warnings will be a list containing these warnings. Returns an iterator when multi is True, otherwise None. """ if not operation: return if self._have_unread_result(): raise errors.InternalError("Unread result found.") self._reset_result() stmt = '' try: if isinstance(operation, unicode): operation = operation.encode(self._connection.charset) except (UnicodeDecodeError, UnicodeEncodeError), e: raise errors.ProgrammingError(str(e))
def _pkt_make_auth(self, username=None, password=None, database=None, seed=None, charset=33, client_flags=0): """Make a MySQL Authentication packet""" try: seed = seed or self.scramble except: raise errors.ProgrammingError('Seed missing') (_username, _password, _database) = self._prepare_auth(username, password, database, client_flags, seed) data = utils.int4store(client_flags) +\ utils.int4store(10 * 1024 * 1024) +\ utils.int1store(charset) +\ '\x00'*23 +\ _username +\ _password +\ _database header = self._pkt_make_header(len(data)) return header + data
def _handle_noresultset(self, res): """Handles result of execute() when there is no result set """ try: self._rowcount = res['affected_rows'] self._last_insert_id = res['insert_id'] self._warning_count = res['warning_count'] except (KeyError, TypeError), err: raise errors.ProgrammingError("Failed handling non-resultset; %s" % err)
def execute(self, operation, params=None): """ Executes the given operation. The parameters given through params are used to substitute %%s in the operation string. For example, getting all rows where id is 5: cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,)) If warnings where generated, and db.get_warnings is True, then self._warnings will be a list containing these warnings. Raises exceptions when any error happens. """ if not operation: return 0 if self.db().unread_result is True: raise errors.InternalError("Unread result found.") self._reset_result() stmt = '' try: if isinstance(operation, unicode): operation = operation.encode(self.db().charset_name) if params is not None: try: stmt = operation % self._process_params(params) except TypeError: raise errors.ProgrammingError( "Wrong number of arguments during string formatting") else: stmt = operation res = self.db().protocol.cmd_query(stmt) self._handle_result(res) except (UnicodeDecodeError,UnicodeEncodeError), e: raise errors.ProgrammingError(str(e))
def _handle_noresultset(self, res): """Handles result of execute() when there is no result set """ try: self.rowcount = res['affected_rows'] self.lastrowid = res['insert_id'] self._warning_count = res['warning_count'] if self.db().get_warnings is True and self._warning_count: self._warnings = self._fetch_warnings() self._set_more_results(res['server_status']) except errors.Error: raise except StandardError, e: raise errors.ProgrammingError( "Failed handling non-resultset; %s" % e)
def _process_params_dict(self, params): try: to_mysql = self.db().converter.to_mysql escape = self.db().converter.escape quote = self.db().converter.quote res = {} for k,v in params.items(): c = v c = to_mysql(c) c = escape(c) c = quote(c) res[k] = c except StandardError, e: raise errors.ProgrammingError( "Failed processing pyformat-parameters; %s" % e)
def _pkt_make_changeuser(self, username=None, password=None, database=None, charset=8, seed=None): """Make a MySQL packet with the Change User command""" try: seed = seed or self.scramble except: raise errors.ProgrammingError('Seed missing') (_username, _password, _database) = self._prepare_auth( username, password, database, self.client_flags, seed) data = utils.int1store(ServerCmd.CHANGE_USER) +\ _username +\ _password +\ _database +\ utils.int2store(charset) return data
def make_change_user(self, seed, username=None, password=None, database=None, charset=33, client_flags=0): """Make a MySQL packet with the Change User command""" if not seed: raise errors.ProgrammingError('Seed missing') auth = self._prepare_auth(username, password, database, client_flags, seed) data = utils.int1store(ServerCmd.CHANGE_USER) +\ auth[0] + auth[1] + auth[2] + utils.int2store(charset) return data
def _pkt_make_auth_ssl(self, username=None, password=None, database=None, seed=None, charset=33, client_flags=0, max_allowed_packet=None): try: seed = seed or self.scramble except: raise errors.ProgrammingError('Seed missing') if max_allowed_packet is None: max_allowed_packet = 1073741824 # 1Gb (_username, _password, _database) = self._prepare_auth( username, password, database, client_flags, seed) data = utils.int4store(client_flags) +\ utils.int4store(max_allowed_packet) +\ utils.int1store(charset) +\ '\x00'*23 return data
def make_auth(self, seed, username=None, password=None, database=None, charset=33, client_flags=0, max_allowed_packet=1073741824): """Make a MySQL Authentication packet""" if not seed: raise errors.ProgrammingError('Seed missing') auth = self._prepare_auth(username, password, database, client_flags, seed) return utils.int4store(client_flags) +\ utils.int4store(max_allowed_packet) +\ utils.int1store(charset) +\ '\x00' * 23 + auth[0] + auth[1] + auth[2]
def cursor(self, buffered=None, raw=None, cursor_class=None): """Instantiates and returns a cursor By default, MySQLCursor is returned. Depending on the options while connecting, a buffered and/or raw cursor instantiated instead. It is possible to also give a custom cursor through the cursor_class paramter, but it needs to be a subclass of mysql.connector.cursor.CursorBase. Returns a cursor-object """ if cursor_class is not None: if not issubclass(cursor_class, cursor.CursorBase): raise errors.ProgrammingError( "Cursor class needs be subclass of cursor.CursorBase") c = (cursor_class)(self) else: buffered = buffered or self.buffered raw = raw or self.raw t = 0 if buffered is True: t |= 1 if raw is True: t |= 2 types = { 0: cursor.MySQLCursor, 1: cursor.MySQLCursorBuffered, 2: cursor.MySQLCursorRaw, 3: cursor.MySQLCursorBufferedRaw, } c = (types[t])(self) if c not in self.cursors: self.cursors.append(c) return c
def cursor(self, buffered=None, raw=None, cursor_class=None): """Instantiates and returns a cursor By default, MySQLCursor is returned. Depending on the options while connecting, a buffered and/or raw cursor instantiated instead. It is possible to also give a custom cursor through the cursor_class paramter, but it needs to be a subclass of mysql.connector.cursor.CursorBase. Returns a cursor-object """ if not self.is_connected(): raise errors.OperationalError("MySQL Connection not available.") if cursor_class is not None: if not issubclass(cursor_class, CursorBase): raise errors.ProgrammingError( "Cursor class needs to be subclass of cursor.CursorBase") return (cursor_class)(self) buffered = buffered or self._buffered raw = raw or self._raw cursor_type = 0 if buffered is True: cursor_type |= 1 if raw is True: cursor_type |= 2 types = ( MySQLCursor, # 0 MySQLCursorBuffered, MySQLCursorRaw, MySQLCursorBufferedRaw, ) return (types[cursor_type])(self)
def remove_cursor(self, c): try: self.cursors.remove(c) except ValueError: raise errors.ProgrammingError("Cursor could not be removed.")
raise errors.InternalError("Unread result found.") self._reset_result() stmt = '' try: if isinstance(operation, unicode): operation = operation.encode(self._connection.charset) except (UnicodeDecodeError, UnicodeEncodeError), e: raise errors.ProgrammingError(str(e)) if params is not None: try: stmt = operation % self._process_params(params) except TypeError: raise errors.ProgrammingError( "Wrong number of arguments during string formatting") else: stmt = operation if multi: self._executed = stmt self._executed_list = [] return self._execute_iter(self._connection.cmd_query_iter(stmt)) else: self._executed = stmt try: self._handle_result(self._connection.cmd_query(stmt)) except errors.InterfaceError, err: if self._connection._have_next_result: raise errors.InterfaceError( "Use multi=True when executing multiple statements")