python连接mysql

        try:
            self.db=MySQLdb.connect(host=self.host,user=self.user,passwd=self.passwd,db=self.dbname,charset="utf8")
            self.db.autocommit(True)
            self.cursor = self.db.cursor()
            self.cursor.execute("SET NAMES utf8")
            self.cursor.execute("SET CHARACTER_SET_CLIENT=utf8")
            self.cursor.execute("SET CHARACTER_SET_RESULTS=utf8")
            self.cursor.execute("SET WAIT_TIMEOUT=100")
            self.cursor.execute("SET INTERACTIVE_TIMEOUT=100")
            print "-----------------------mysql connect to %s-----------------------" %(self.host)
            sys.stdout.flush()
        except MySQLdb.Error, e:
            print "re_connect Error %d: %s " % (e.args[0], e.args[1])
            sys.stdout.flush()


self.cursor.execute("SET WAIT_TIMEOUT=100")

self.cursor.execute("SET INTERACTIVE_TIMEOUT=100")

这两句设置使一直运行的程序不用频繁的连接断开mysql,增加mysql的开销

 

ps:mysql的三种timeout

  connect_timeout 在connect函数中设置

  The number of seconds that the mysqld server waits for a connect packet before responding with Bad handshake.

  interactive_timeout

  The number of seconds the server waits for activity on an interactive connection before closing it.

  wait_timeout

  The number of seconds the server waits for activity on a noninteractive connection before closing it.

 

你可能感兴趣的:(python连接mysql)