MySQL服务器已经消失了

时间:2015-04-20 09:59:04

标签: python mysql

我是python中的新手,所以,它看起来像是我在lang上的第一个项目。 每当我试图运行我的脚本时 - 我从mysql服务器得到不同的答案 最常见的答案是OperationalError: (2006, 'MySQL server has gone away') 有时我得到输出Thread: 11 commited(参见下面的代码) 有时emergency stop(翻译,我在控制台有俄语输出) 无论输出是否满commited - 表中的记录仍然相同。

import MySQLdb
import pyping
import socket, struct
from threading import Thread

def ip2int(addr):
    """Convert ip to integer"""
    return struct.unpack("!I", socket.inet_aton(addr))[0]

def int2ip(addr):
    """Convert integer to ip"""
    return socket.inet_ntoa(struct.pack("!I", addr))

def ping(ip):
    """Pinging client"""
    request = pyping.ping(ip, timeout=100, count=1)
    return int(request.max_rtt)

class UpdateThread(Thread):
    def __init__(self, records, name):
        Thread.__init__(self)
        self.database = MySQLdb.connect(host="***", port=3306, user="root", passwd="***", db="dns")
        self.cursor = database.cursor()
        self.name = name
        self.records = records
    def run(self):
        print(self.name)
        for r in self.records:
            #latency = ping(int2ip(r[1])) what the hell :x
            #ip = str(int2ip(r[1]))
            id = str(r[0])
            self.cursor.execute("""update clients set has_subn=%s where id=%s""" % (id, id))
        self.database.commit()
        print(self.name + " commited")

#start
database = MySQLdb.connect(host="***", port=3306, user="root", passwd="***", db="dns")
cursor = database.cursor()
cursor.execute("""select * from clients""")
data = cursor.fetchall() #All records from DataBase
count = len(data) 
threads_counter = 10 #We are creating 10 threads for all records
th_count = count / threads_counter #Count of records for each thread
last_thread = count % threads_counter #Last records
threads = []

i = 0
while i < (count - last_thread):
    temp_list = data[i:(i+th_count)]
    #print(temp_list)
    threads.append(UpdateThread(records = temp_list, name = "Thread: " + str((i/3) + 1)).start())
    i += th_count

threads.append(UpdateThread(records = data[i: count], name = "Thread: 11").start())

P.S。
我在这里找到的另一个答案并没有帮助我。

UPD:
我发现有些(每次都是另一个)线程打印
OperationalError: (2013, 'Lost connection to MySQL server during query')以及所有下一个帖子都打印OperationalError: (2013, 'Lost connection to MySQL server during query')

1 个答案:

答案 0 :(得分:0)

当您完成数据库连接时,您需要关闭数据库连接,否则数据库服务器将不堪重负并使您的连接过期。对于您的程序,我会更改您的代码,以便您只有一个数据库连接。您可以将对它的引用传递给UpdateThread实例,并在完成后关闭它。

database.close()