我有一个python多处理套接字程序。我使用mysql查询来根据每个套接字连接获取数据。我的代码暂存如下:
import multiprocessing
import MySQLdb
import socket
import sys
import os
def handle(connection, address):
try:
while True:
#at some condition
cursor.execute("SELECT a, b, c, d FROM table1 WHERE idx=%s", (somevalue))
result1 = cursor.fetchone()
#another condition
cursor.execute("SELECT e, f, g FROM table2 WHERE idx=%s", (somevalue))
result2 = cursor.fetchone()
except:
logger.exception("Problem handling request")
finally:
#logger.debug("Closing socket")
#connection.close()
pass
class Server(object):
def __init__(self, hostname, port):
import logging
self.logger = logging.getLogger("server")
self.hostname = hostname
self.port = port
def start(self):
self.logger.debug("listening")
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind((self.hostname, self.port))
self.socket.listen(1)
while True:
conn, address = self.socket.accept()
self.logger.debug("Got connection")
#starting multi process
process = multiprocessing.Process(target=handle, args=(conn, address))
#process.daemon = True
process.start()
self.logger.debug("Started process %r", process)
if __name__ == "__main__":
import logging
#db connection configuration
db = MySQLdb.connect("host", "username", "password", "db")
cursor = db.cursor()
logging.basicConfig(level=logging.DEBUG)
#server ip and port configuration
server = Server("host", port)
try:
#server start to listen socket
logging.info("Listening")
server.start()
except:
logging.exception("Unexpected exception")
finally:
logging.info("Shutting down")
for process in multiprocessing.active_children():
logging.info("Shutting down process %r", process)
process.terminate()
process.join()
logging.info("All done")
该程序可以正常运行一段时间。之后,执行result1的查询作为result2的查询。即,将result1分配给result2。我想念什么?
我尝试了db.commit()并在每次查询后打开和关闭游标。
我是否必须使用Lock and Release或清除缓存mysql?