python MySQLdb 连接数据库太耗时

图片说明

 #!usr/bin/python
#!coding:utf-8

import MySQLdb
import threading
from config.config import Config
from Clogger.logger import CLogger
import time


class Positions(object):
    __instance = None
    __positions = None
    __index = 0
    __Lock = None
    __size = 0

    def __init__(self):
        pass


    def __del__(self):
        Positions.__instance = None
        Positions.__positions = None
        Positions.__index = 0
        Positions.__Lock = None
        Positions.__size = 0


    def __new__(cls, *args, **kwargs):
        Positions.__Lock = threading.Lock()
        if not cls.__instance:
            try:
                Positions.__Lock.acquire()
                if not cls.__instance:
                    cls.__instance = super(Positions, cls).__new__(cls, *args, **kwargs)
                    cls.__instance.selectAll()
            finally:
                Positions.__Lock.release()


    def selectAll(self):
        try:
            print time.time()
            conn = MySQLdb.connect(
                host=Config.mysql_host,
                port=Config.mysql_port,
                user=Config.mysql_user,
                passwd=Config.mysql_password,
                db=Config.mysql_db,
                charset="utf8"
            )
            print time.time()
            cursor = conn.cursor()
        except Exception, e:
            CLogger.logger().error(str(e))
            exit()
        sql1 = "select towncode from addressComponents where province='%s' and city = '%s' and towncode is not null " \
               "group by towncode" % (Config.current_province, Config.current_city)
        sql = "select lng, lat from pois where towncode in (%s);" % sql1
        cursor.execute(sql)
        Positions.__positions = cursor.fetchall()
        Positions.__size = len(Positions.__positions)
        print Positions.__size
        if Positions.__size <= 0:
            CLogger.logger().info(str(Positions.__size))
            exit(-1)


    @staticmethod
    def getPosition():
        if not Positions.__instance:
            Positions.__new__()
        try:
            Positions.__Lock.acquire()
            index = Positions.__index
            Positions.__index += 1
            Positions.__Lock.release()
            if index >= Positions.__size:
                return "Empty"
            return Positions.__positions[index]
        except Exception, e:
            CLogger.logger().error(str(e))

3个回答

跟python代码没关系,看看mysql配置文件my.cnf

这个主要是MySQL设置或者网络连接的问题,可以看看关闭MySQL的DNS反向解析,在MY.INI(WINDOWS系统下)或MY.CNF(UNIX或LINUX系统下)文件的[mysqld]下加入skip-name-resolve

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐