📄 cursors.py
字号:
"""MySQLdb CursorsThis module implements Cursors of various types for MySQLdb. Bydefault, MySQLdb uses the Cursor class."""import reinsert_values = re.compile(r"\svalues\s*(\(((?<!\\)'.*?\).*(?<!\\)?'|.)+?\))", re.IGNORECASE)from _mysql_exceptions import Warning, Error, InterfaceError, DataError, \ DatabaseError, OperationalError, IntegrityError, InternalError, \ NotSupportedError, ProgrammingErrorclass BaseCursor(object): """A base for Cursor classes. Useful attributes: description A tuple of DB API 7-tuples describing the columns in the last executed query; see PEP-249 for details. description_flags Tuple of column flags for last query, one entry per column in the result set. Values correspond to those in MySQLdb.constants.FLAG. See MySQL documentation (C API) for more information. Non-standard extension. arraysize default number of rows fetchmany() will fetch """ from _mysql_exceptions import MySQLError, Warning, Error, InterfaceError, \ DatabaseError, DataError, OperationalError, IntegrityError, \ InternalError, ProgrammingError, NotSupportedError _defer_warnings = False def __init__(self, connection): from weakref import proxy self.connection = proxy(connection) self.description = None self.description_flags = None self.rowcount = -1 self.arraysize = 1 self._executed = None self.lastrowid = None self.messages = [] self.errorhandler = connection.errorhandler self._result = None self._warnings = 0 self._info = None self.rownumber = None def __del__(self): self.close() self.errorhandler = None self._result = None def close(self): """Close the cursor. No further queries will be possible.""" if not self.connection: return while self.nextset(): pass self.connection = None def _check_executed(self): if not self._executed: self.errorhandler(self, ProgrammingError, "execute() first") def _warning_check(self): from warnings import warn if self._warnings: warnings = self._get_db().show_warnings() if warnings: # This is done in two loops in case # Warnings are set to raise exceptions. for w in warnings: self.messages.append((self.Warning, w)) for w in warnings: warn(w[-1], self.Warning, 3) elif self._info: self.messages.append((self.Warning, self._info)) warn(self._info, self.Warning, 3) def nextset(self): """Advance to the next result set. Returns None if there are no more result sets. """ if self._executed: self.fetchall() del self.messages[:] db = self._get_db() nr = db.next_result() if nr == -1: return None self._do_get_result() self._post_get_result() self._warning_check() return 1 def _post_get_result(self): pass def _do_get_result(self): db = self._get_db() self._result = self._get_result() self.rowcount = db.affected_rows() self.rownumber = 0 self.description = self._result and self._result.describe() or None self.description_flags = self._result and self._result.field_flags() or None self.lastrowid = db.insert_id() self._warnings = db.warning_count() self._info = db.info() def setinputsizes(self, *args): """Does nothing, required by DB API.""" def setoutputsizes(self, *args): """Does nothing, required by DB API.""" def _get_db(self): if not self.connection: self.errorhandler(self, ProgrammingError, "cursor closed") return self.connection def execute(self, query, args=None): """Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any """ from types import ListType, TupleType from sys import exc_info del self.messages[:] db = self._get_db() charset = db.character_set_name() if isinstance(query, unicode): query = query.encode(charset) if args is not None: query = query % db.literal(args) try: r = self._query(query) except TypeError, m: if m.args[0] in ("not enough arguments for format string", "not all arguments converted"): self.messages.append((ProgrammingError, m.args[0])) self.errorhandler(self, ProgrammingError, m.args[0]) else: self.messages.append((TypeError, m)) self.errorhandler(self, TypeError, m) except: exc, value, tb = exc_info() del tb self.messages.append((exc, value)) self.errorhandler(self, exc, value) self._executed = query if not self._defer_warnings: self._warning_check() return r def executemany(self, query, args): """Execute a multi-row query. query -- string, query to execute on server args Sequence of sequences or mappings, parameters to use with query. Returns long integer rows affected, if any. This method improves performance on multiple-row INSERT and REPLACE. Otherwise it is equivalent to looping over args with execute(). """ del self.messages[:] db = self._get_db() if not args: return charset = db.character_set_name() if isinstance(query, unicode): query = query.encode(charset) m = insert_values.search(query) if not m: r = 0 for a in args: r = r + self.execute(query, a) return r p = m.start(1) e = m.end(1) qv = m.group(1) try: q = [ qv % db.literal(a) for a in args ] except TypeError, msg: if msg.args[0] in ("not enough arguments for format string", "not all arguments converted"): self.messages.append((ProgrammingError, msg.args[0])) self.errorhandler(self, ProgrammingError, msg.args[0]) else: self.messages.append((TypeError, msg)) self.errorhandler(self, TypeError, msg) except: from sys import exc_info exc, value, tb = exc_info() del tb self.errorhandler(self, exc, value) r = self._query('\n'.join([query[:p], ',\n'.join(q), query[e:]])) if not self._defer_warnings: self._warning_check() return r def callproc(self, procname, args=()): """Execute stored procedure procname with args procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any modified parameters must be returned. This is currently impossible as they are only available by storing them in a server variable and then retrieved by a query. Since stored procedures return zero or more result sets, there is no reliable way to get at OUT or INOUT parameters via callproc. The server variables are named @_procname_n, where procname is the parameter above and n is the position of the parameter (from zero). Once all result sets generated by the procedure have been fetched, you can issue a SELECT @_procname_0, ... query using .execute() to get any OUT or INOUT values. Compatibility warning: The act of calling a stored procedure itself creates an empty result set. This appears after any result sets generated by the procedure. This is non-standard behavior with respect to the DB-API. Be sure to use nextset() to advance through all result sets; otherwise you may get disconnected. """
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -