【问题标题】:How to check if a MySQL connection is open in Python?如何检查 MySQL 连接是否在 Python 中打开?
【发布时间】:2016-01-19 06:42:36
【问题描述】:

我正在使用 MySQLdb (http://mysql-python.sourceforge.net/)。似乎 connection.open 和 connection.sqlstate() 对我不起作用。下面是代码:

def open(self):
    #TODO: check the connection's status
    # self.__conn.open OR self.__conn.sqlstate()
    try:
        print "sqlstate:"+str( self.__conn.sqlstate() )
        print "open?"+str( self.__conn.open )
        return "00000" == self.__conn.sqlstate()
    except Exception as e:
        print "Exception while checking MYSQL Connection:"+str(e) 
        return False

但是当我运行“sudo service mysql stop; sleep 60; sudo service mysql start;”时做测试。输出如下。似乎以下输出永远重复(我最终终止了该过程)。当服务器关闭时,connection.open 为 1,connection.sqlstate() 为 00000。但是当服务器启动时,connection.executemany() 仍然会抛出异常。有任何想法吗?谢谢。

...
    2015-10-20 14:09:06 Exception while executing statement:(2006, 'MySQL server has gone away')
    2015-10-20 14:09:06 sqlstate:00000
    2015-10-20 14:09:06 open?1
    2015-10-20 14:09:06 Reconnected to MYSQL.
    2015-10-20 14:09:06 Exception while executing statement:(2006, 'MySQL server has gone away')
    2015-10-20 14:09:06 sqlstate:00000
    2015-10-20 14:09:06 open?1
    2015-10-20 14:09:06 Reconnected to MYSQL.
    2015-10-20 14:09:06 Exception while executing statement:(2006, 'MySQL server has gone away')
    2015-10-20 14:09:06 sqlstate:00000
    2015-10-20 14:09:06 open?1
    2015-10-20 14:09:06 Reconnected to MYSQL.
    2015-10-20 14:09:06 Exception while executing statement:(2006, 'MySQL server has gone away')
    2015-10-20 14:09:06 sqlstate:00000
    2015-10-20 14:09:06 open?1
...

更新

我再次测试。输出如下。每次睡眠时间为 10 秒。输出正常,除了 connection.open 为 1,即使服务器关闭。但是connection.sqlstate()是对的(HY000)。

 2015-10-20 14:35:56 Exception while executing statement:(2006, 'MySQL server has gone away')
2015-10-20 14:35:56 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:35:56 sqlstate:HY000
2015-10-20 14:35:56 open?1
2015-10-20 14:35:56 sleeping...
2015-10-20 14:36:06 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:06 sqlstate:HY000
2015-10-20 14:36:06 open?1
2015-10-20 14:36:06 sleeping...
2015-10-20 14:36:16 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:16 sqlstate:HY000
2015-10-20 14:36:16 open?1
2015-10-20 14:36:16 sleeping...
2015-10-20 14:36:26 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:26 sqlstate:HY000
2015-10-20 14:36:26 open?1
2015-10-20 14:36:26 sleeping...
2015-10-20 14:36:36 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:36 sqlstate:HY000
2015-10-20 14:36:36 open?1
2015-10-20 14:36:36 sleeping...
2015-10-20 14:36:46 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:46 sqlstate:HY000
2015-10-20 14:36:46 open?1
2015-10-20 14:36:46 sleeping...
2015-10-20 14:36:56 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:56 sqlstate:HY000
2015-10-20 14:36:56 open?1
2015-10-20 14:36:56 sleeping...
2015-10-20 14:37:06 sqlstate:00000
2015-10-20 14:37:06 open?1
2015-10-20 14:37:06 Reconnected to MYSQL.

【问题讨论】:

    标签: python mysql mysql-python


    【解决方案1】:

    你可以通过这个库python-mysql的is_connected方法检查连接:

    cnx = connector.connect(user="user",password="pass",host="host",database="database")
    
    if (cnx.is_connected()):
        print("Connected")
    else:
        print("Not connected")
    

    【讨论】:

      【解决方案2】:

      试试这个-

      import MySQLdb
      
      def main():
        # Connect to the MySQL database
        db = MySQLdb.connect(host = 'z.cs.utexas.edu', user = 'userName', passwd = 'password', db = 'dbName')
      
        # Check if connection was successful
        if (db):
          # Carry out normal procedure
          print "Connection successful"
        else:
          # Terminate
          print "Connection unsuccessful"
      

      【讨论】:

      • 这对于检查MysqlConnection 对象是否已实例化或是否已建立连接很有用。它不验证连接是否还活着
      【解决方案3】:

      我一直在寻找这个解决方案一段时间,但我找不到一个优雅的解决方案。

      似乎没有直接的方法可以做到这一点。如果您尝试执行查询,您只会发现您的连接已关闭。

      我最终做了类似于这个答案的事情: How to check the connection alive in python?

      【讨论】:

        【解决方案4】:

        你应该这样编码: 在每次执行之前,ping mysql-server,例如

        import MySQLdb as db
            class DB(object):
                def __init__(self):
                    try:
                        self.conn =mdb.connect(host='***',port=3306,user='',passwd='')
                    if (self.conn):
                        INFO_LOG("DB init success")
                    else:
                        INFO_LOG("DB init fail")
                    self.conn.autocommit(True)
                    self.conn.select_db(DB_NAME)
                    self.cursor = self.conn.cursor()
                except Exception as e:
                    CRITICAL_LOG("DB init fail %s " % str(e))
            def insert(self,player_id,cmd):
                try:
                    if self.conn is None:
                        self.__init__()
                    else:
                        self.conn.ping(True)
                    self.cursor.execute('INSERT INTO table values("%s",%s")' %
                    (player_id,cmd))
                except Exception as e:
                    import traceback
                    traceback.print_exc()
                    #error ocurs,rollback
                    self.conn.rollback()
        

        【讨论】:

          【解决方案5】:

          以防万一有人觉得这有帮助:

          import socket
          import time
          sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
          while sock.connect_ex(('db', 3306)) != 0: # 'db' is the host, 3306 is the port
              print('MySQL is not ready yet.')
              time.sleep(2)
          sock.close()
          print("Now it's up and running! Bye!")
          

          【讨论】:

          • 不好的做法也是错误的答案。 “socket.gaierror:[Errno 11001] getaddrinfo 失败”
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-27
          • 2013-04-25
          • 2016-04-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多