當前位置: 首頁>>代碼示例>>Python>>正文


Python MySQLdb.OperationalError方法代碼示例

本文整理匯總了Python中MySQLdb.OperationalError方法的典型用法代碼示例。如果您正苦於以下問題:Python MySQLdb.OperationalError方法的具體用法?Python MySQLdb.OperationalError怎麽用?Python MySQLdb.OperationalError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在MySQLdb的用法示例。


在下文中一共展示了MySQLdb.OperationalError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: buildDatabase

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def buildDatabase( databaseName ):

   username = raw_input( "Enter MySQL user name: " )
   password = getpass.getpass( "Enter user password: " )

   print "Creating database %s:" % databaseName

   # retrieve database description from file
   print "\tRetrieving database definition:",

   try:
      databaseDefinition = retrieveDatabaseDefinition( databaseName )
   except TypeError:
      sys.exit( "ERROR\nThe database definition in %s.def is invalid" % databaseName )
   else:
      print "DONE"

   # get a cursor for MySQL
   print "\tConnecting to MySQL:",
   try:
      cursor = MySQLdb.connect( user = username, passwd = password ).cursor()
   except MySQLdb.OperationalError, error:
      sys.exit( "ERROR\nCould not connect to MySQL (%s)" % error ) 
開發者ID:PythonClassRoom,項目名稱:PythonClassBook,代碼行數:25,代碼來源:DBSetup.py

示例2: execute_with_reconnect

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def execute_with_reconnect(self, sql: str, args: Optional[List[ValidSqlArgumentDescription]] = None, fetch_rows: Optional[bool] = False) -> Tuple[int, List[ValidSqlArgumentDescription]]:
        result = None
        # Attempt to execute the query and reconnect 3 times, then give up
        for _ in range(3):
            try:
                p = perf.start()
                n = self.cursor.execute(sql, args)
                perf.check(p, 'slow_query', (f'```{sql}```', f'```{args}```'), 'mysql')
                if fetch_rows:
                    rows = self.cursor.fetchall()
                    result = (n, rows)
                else:
                    result = (n, [])
                break
            except OperationalError as e:
                if 'MySQL server has gone away' in str(e):
                    print('MySQL server has gone away: trying to reconnect')
                    self.connect()
                else:
                    # raise any other exception
                    raise e
        else:
            # all attempts failed
            raise DatabaseException('Failed to execute `{sql}` with `{args}`. MySQL has gone away and it was not possible to reconnect in 3 attemps'.format(sql=sql, args=args))
        return result 
開發者ID:PennyDreadfulMTG,項目名稱:Penny-Dreadful-Tools,代碼行數:27,代碼來源:database.py

示例3: setup_audit_plugin

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def setup_audit_plugin(instance):
    """ Install the audit log plugin.  Similarly to semisync, we may
        or may not use it, but we need to make sure that it's available.
        Audit plugin is available on 5.5 and above, which are all the
        versions we support.

        Args:
        instance - A hostaddr object
    """
    return 
    # this is intentional; we may re-enable the audit log at some 
    # later date, but for now, we just exit.

    conn = connect_mysql(instance)
    cursor = conn.cursor()

    try:
        cursor.execute("INSTALL PLUGIN audit_log SONAME 'audit_log.so'")
    except MySQLdb.OperationalError as detail:
        (error_code, msg) = detail.args
        # plugin already loaded, nothing to do.
        if error_code != MYSQL_ERROR_FUNCTION_EXISTS:
            raise
    conn.close() 
開發者ID:pinterest,項目名稱:mysql_utils,代碼行數:26,代碼來源:mysql_lib.py

示例4: query

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def query(self, sql, use_dict=True, retry=0):

        if retry < 0:
            retry = 0

        retry = int(retry)

        # the first attempt does not count as 'retry'
        for i in range(retry + 1):

            try:
                with self() as conn:
                    return conn_query(conn, sql, use_dict=use_dict)

            except MySQLdb.OperationalError as e:
                if len(e.args) > 0 and e[0] in retriable_err:
                    logger.info(
                        repr(e) + " conn_query error {sql}".format(sql=sql))
                    continue
                else:
                    raise
        else:
            raise 
開發者ID:bsc-s2,項目名稱:pykit,代碼行數:25,代碼來源:mysqlconnpool.py

示例5: _purge_bitmaps_to

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def _purge_bitmaps_to(lsn):
    _say("Purging bitmap files to LSN: %s" % lsn)

    if not db_connect():
        _error("Failed to connect to server, unable to purge bitmaps.")
        _exit_code(XB_EXIT_BITMAP_PURGE_FAIL)
        return False

    try:
        cur = xb_mysqldb.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("PURGE CHANGED_PAGE_BITMAPS BEFORE %s" % lsn)
    except MySQLdb.OperationalError, e:
        _error("Got MySQL error %d, \"%s\" at execute" % (e.args[0], e.args[1]))
        _error("Failed to purge bitmaps!")
        _exit_code(XB_EXIT_BITMAP_PURGE_FAIL)
        return False 
開發者ID:dotmanila,項目名稱:pyxbackup,代碼行數:18,代碼來源:pyxbackup.py

示例6: job_runner

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def job_runner(f):
    """Accepts any callable function and runs it

    Catches any exceptions and logs to Rollbar
    """
    result = None
    try:
        ensure_mysql_connection_usable()
        result = f()
    except MySQLdb.OperationalError as e:
        extra_data = {
            'caught_exception' : True,
            'attempt_reconnect' : True,
        }
        rollbar.report_exc_info(extra_data=extra_data)
        attempt_mysql_reconnect()
    except:
        rollbar.report_exc_info()
    finally:
        close_connection()
    return result 
開發者ID:hacktoolkit,項目名稱:django-htk,代碼行數:23,代碼來源:utils.py

示例7: addAddress

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def addAddress( self ):
      """Add address record to database"""

      if self.entries[ "LAST_NAME" ].get() != "" and \
         self.entries[ "FIRST_NAME"].get() != "":

         # create INSERT query command
         query = """INSERT INTO addresses (  
                 FIRST_NAME, LAST_NAME, ADDRESS, CITY,
                 STATE_PROVINCE, POSTAL_CODE, COUNTRY,
                 EMAIL_ADDRESS, HOME_PHONE, FAX_NUMBER
                 ) VALUES (""" + \
                 "'%s', " * 10 % \
                 ( self.entries[ "FIRST_NAME" ].get(),
                   self.entries[ "LAST_NAME" ].get(),
                   self.entries[ "ADDRESS" ].get(),
                   self.entries[ "CITY" ].get(),
                   self.entries[ "STATE_PROVINCE" ].get(),
                   self.entries[ "POSTAL_CODE" ].get(),
                   self.entries[ "COUNTRY" ].get(),
                   self.entries[ "EMAIL_ADDRESS" ].get(),
                   self.entries[ "HOME_PHONE" ].get(),
                   self.entries[ "FAX_NUMBER" ].get() )
         query = query[ :-2 ] + ")"

         # open connection, retrieve cursor and execute query
         try:      
            connection = MySQLdb.connect( db = "AddressBook" )
            cursor = connection.cursor()
            cursor.execute( query ) 
         except MySQLdb.OperationalError, message:
            errorMessage = "Error %d:\n%s" % \
               ( message[ 0 ], message[ 1 ] )
            showerror( "Error", errorMessage )
         else:
            cursor.close()
            connection.close()
	    self.clearContents() 
開發者ID:PythonClassRoom,項目名稱:PythonClassBook,代碼行數:40,代碼來源:fig17_30.py

示例8: findAddress

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def findAddress( self ):
      """Query database for address record and display results"""

      if self.entries[ "LAST_NAME" ].get() != "":

         # create SELECT query
         query = "SELECT * FROM addresses " + \
                 "WHERE LAST_NAME = '" + \
                 self.entries[ "LAST_NAME" ].get() + "'"

         # open connection, retrieve cursor and execute query
         try:      
            connection = MySQLdb.connect( db = "AddressBook" )
            cursor = connection.cursor()
            cursor.execute( query )
         except MySQLdb.OperationalError, message:
            errorMessage = "Error %d:\n%s" % \
               ( message[ 0 ], message[ 1 ] )
            showerror( "Error", errorMessage )
            self.clearContents()
         else:   # process results
            results = cursor.fetchall()
            fields = cursor.description

            if not results:   # no results for this person
               showinfo( "Not found", "Nonexistent record" )
            else:             # display person's info. in GUI
               self.clearContents()

               # display results
               for i in range( len( fields ) ):

                  if fields[ i ][ 0 ] == "ID":
                     self.IDEntry.set( str( results[ 0 ][ i ] ) )
                  else:
                     self.entries[ fields[ i ][ 0 ] ].insert( 
                        INSERT, str( results[ 0 ][ i ] ) )
            
            cursor.close()
            connection.close() 
開發者ID:PythonClassRoom,項目名稱:PythonClassBook,代碼行數:42,代碼來源:fig17_30.py

示例9: updateAddress

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def updateAddress( self ):
      """Update address record in database"""

      if self.entries[ "ID" ].get() != "":

         # create UPDATE query command
         entryItems = self.entries.items()
         query = "UPDATE addresses SET"

         for key, value in entryItems:
            
            if key != "ID":
               query += " %s='%s'," % ( key, value.get() )

         query = query[ :-1 ] + " WHERE ID=" + self.IDEntry.get()

         # open connection, retrieve cursor and execute query
         try:      
            connection = MySQLdb.connect( db = "AddressBook" )
            cursor = connection.cursor()
            cursor.execute( query ) 
         except MySQLdb.OperationalError, message:
            errorMessage = "Error %d:\n%s" % \
               ( message[ 0 ], message[ 1 ] )
            showerror( "Error", errorMessage )
            self.clearContents()
         else:
            showinfo( "database updated", "Database Updated." )
            cursor.close()
            connection.close() 
開發者ID:PythonClassRoom,項目名稱:PythonClassBook,代碼行數:32,代碼來源:fig17_30.py

示例10: submitQuery

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def submitQuery( self ):
      """Execute user-entered query agains database"""

      # open connection, retrieve cursor and execute query
      try:      
         connection = MySQLdb.connect( db = "Books" )
         cursor = connection.cursor()
         cursor.execute( self.query.get() )
      except MySQLdb.OperationalError, message:
         errorMessage = "Error %d:\n%s" % \
            ( message[ 0 ], message[ 1 ] )
         showerror( "Error", errorMessage )
         return 
開發者ID:PythonClassRoom,項目名稱:PythonClassBook,代碼行數:15,代碼來源:fig17_29.py

示例11: process_exception

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def process_exception(self, request, exception):
        import traceback
        exc_info = sys.exc_info()
        try:
            format = traceback.format_exc(exc_info[2])
        except:
            format = ''
        message = str(exception)
        if (isinstance(exception, IOError) and '_verify(ticket, service)' in format
            and ('Connection reset by peer' in message
                 or 'Name or service not known' in message
                 or 'Connection timed out' in message
                 or 'EOF occurred in violation of protocol' in message)):
            # CAS verification timeout
            return HttpError(request, status=500, title="CAS Error", error="Could not contact the CAS server to verify your credentials. Please try logging in again.")
        elif isinstance(exception, AssertionError) and "Django CAS middleware requires authentication middleware" in format:
            # CAS choke
            return HttpError(request, status=500, title="CAS Error", error="Could not contact the CAS server to verify your credentials. Please try logging in again.")
        elif isinstance(exception, EOFError) and "return request.POST.get('csrfmiddlewaretoken', '')" in format:
            # file upload EOF
            return HttpError(request, status=500, title="Upload Error", error="Upload seems to have not completed properly.")
        elif OperationalError is not None and isinstance(exception, OperationalError) and "Lost connection to MySQL server at 'reading initial communication packet'" in format:
            # lost main DB
            return HttpError(request, status=500, title="Database Error", error="Unable to connect to database.")
        elif OperationalError is not None and isinstance(exception, OperationalError) and "MySQL server has gone away" in format:
            # lost main DB
            return HttpError(request, status=500, title="Database Error", error="Unable to connect to database.")
        elif isinstance(exception, AssertionError) and "The Django CAS middleware requires authentication middleware" in format:
            # wacky authentication thing that means the database is missing, or something
            return HttpError(request, status=500, title="Database Error", error="Unable to connect to database.") 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:32,代碼來源:middleware.py

示例12: setup_semisync_plugins

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def setup_semisync_plugins(instance):
    """ Install the semi-sync replication plugins.  We may or may
        not actually use them on any given replica set, but this
        ensures that we've got them.  Semi-sync exists on all versions
        of MySQL that we might support, but we'll never use it on 5.5.

        Args:
        instance - A hostaddr object
    """
    conn = connect_mysql(instance)
    cursor = conn.cursor()

    version = get_global_variables(instance)['version']
    if version[0:3] == '5.5':
        return

    try:
        cursor.execute("INSTALL PLUGIN rpl_semi_sync_master SONAME 'semisync_master.so'")
    except MySQLdb.OperationalError as detail:
        (error_code, msg) = detail.args
        if error_code != MYSQL_ERROR_FUNCTION_EXISTS:
            raise
        # already loaded, no work to do

    try:
        cursor.execute("INSTALL PLUGIN rpl_semi_sync_slave SONAME 'semisync_slave.so'")
    except MySQLdb.OperationalError as detail:
        (error_code, msg) = detail.args
        if error_code != MYSQL_ERROR_FUNCTION_EXISTS:
            raise 
開發者ID:pinterest,項目名稱:mysql_utils,代碼行數:32,代碼來源:mysql_lib.py

示例13: query

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def query(self, sql):
        """ Executes the given SQL statement and returns a sequence of rows. """
        assert self.cursor, "%s already closed?" % (self,)
        try:
            self.cursor.execute(sql)
        except MySQLdb.OperationalError, (errcode, msg):
            if errcode != 2006:  # "MySQL server has gone away"
                raise
            self._reconnect() 
開發者ID:pinterest,項目名稱:mysql_utils,代碼行數:11,代碼來源:mysql.py

示例14: execute

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def execute(self, query, args=None):
        try:
            # args is None means no string interpolation
            return self.cursor.execute(query, args)
        except Database.OperationalError as e:
            # Map some error codes to IntegrityError, since they seem to be
            # misclassified and Django would prefer the more logical place.
            if e.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:12,代碼來源:base.py

示例15: executemany

# 需要導入模塊: import MySQLdb [as 別名]
# 或者: from MySQLdb import OperationalError [as 別名]
def executemany(self, query, args):
        try:
            return self.cursor.executemany(query, args)
        except Database.OperationalError as e:
            # Map some error codes to IntegrityError, since they seem to be
            # misclassified and Django would prefer the more logical place.
            if e.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:11,代碼來源:base.py


注:本文中的MySQLdb.OperationalError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。