[Tutor] a question about MySQLdb in python

贾晓磊 jiaxiaolei19871112 at gmail.com
Tue Jan 10 11:25:36 CET 2012


hi, all:

 python's version:  2.6.
 MySQLdb version: 1.2.3.

I once encounter with a question like this:
File
"/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3-py2.6-linux-x86_64.egg/MySQLdb/connections.py",

line 36, in defaulterrorhandler
    raise errorclass, errorvalue
OperationalError: (2006, 'MySQL server has gone away')

and i try to find the exception is how to perform to us in the source code.

when i read the source code, some questions puzzled me!

question 1: how to find the words "2006, 'MySQL server has gone away" in
sourced code?
question 2:  in MySQLdb/cursors.py , the method errorhandler() just receive
two parameters such as exc,value when it's be invoked. however, in
MySQLdb/connection.py, we define it as one receives 4 parameters such
connection, cursor, erorclass, errorvalue
                  a method should accepts 4 parameters is invoked by 2
parameters. how to explain it?
question 3: in MySQLdb/connection.py,  the module cursors is been imported.
 while,  In MySQLdb/cursors.py, some  methods such as errorhandler in
MySQLdb/connection.py is been invoked.
                the two module, which one is execute first?  which one is
added to mem first?


some important codes are shown as follows.

any response will be welcome!

-- Jia Xiaolei

-----------------------------------------------------------------------------------
 source code about MySQLdb
------------------------------------------------------
# MySQLdb/connections.py

import cursors

def defaulterrorhandler(connection, cursor, errorclass, errorvalue):
    """

    If cursor is not None, (errorclass, errorvalue) is appended to
    cursor.messages; otherwise it is appended to
    connection.messages. Then errorclass is raised with errorvalue as
    the value.

    You can override this with your own error handler by assigning it
    to the instance.

    """
    error = errorclass, errorvalue
    if cursor:
        cursor.messages.append(error)
    else:
        connection.messages.append(error)
    del cursor
    del connection
    raise errorclass, errorvalue

class Connection(_mysql.connection):

    """MySQL Database Connection Object"""

    default_cursor = cursors.Cursor
    errorhandler = defaulterrorhandler

    def __init__(self, *args, **kwargs):
         # some codes
         self.cursorclass = kwargs2.pop('cursorclass', self.default_cursor)
        charset = kwargs2.pop('charset', '')

     def cursor(self, cursorclass=None):
        """

        Create a cursor on which queries may be performed. The
        optional cursorclass parameter is used to create the
        Cursor. By default, self.cursorclass=cursors.Cursor is
        used.

        """
        return (cursorclass or self.cursorclass)(self)

    def xx(yy):
         # some codes


 # MySQLdb/cursors.py

class BaseCursor(object):
    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 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

    class Cursor(CursorStoreResultMixIn, CursorTupleRowsMixIn,
             BaseCursor):
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120110/160121d5/attachment.html>


More information about the Tutor mailing list