【发布时间】:2014-08-13 23:21:44
【问题描述】:
我正在尝试设置 MySQL 连接池,并让我的工作进程访问已建立的池,而不是每次都设置新连接。
我很困惑是否应该将数据库游标传递给每个进程,或者是否有其他方法可以做到这一点? MySql.connector 不应该自动进行池化吗?当我检查我的日志文件时,打开和关闭了许多连接......每个进程一个。
我的代码如下所示:
PATH = "/tmp"
class DB(object):
def __init__(self):
connected = False
while not connected:
try:
cnxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name = "pool1",
**config.dbconfig)
self.__cnx = cnxpool.get_connection()
except mysql.connector.errors.PoolError:
print("Sleeping.. (Pool Error)")
sleep(5)
except mysql.connector.errors.DatabaseError:
print("Sleeping.. (Database Error)")
sleep(5)
self.__cur = self.__cnx.cursor(cursor_class=MySQLCursorDict)
def execute(self, query):
return self.__cur.execute(query)
def isValidFile(self, name):
return True
def readfile(self, fname):
d = DB()
d.execute("""INSERT INTO users (first_name) VALUES ('michael')""")
def main():
queue = multiprocessing.Queue()
pool = multiprocessing.Pool(None, init, [queue])
for dirpath, dirnames, filenames in os.walk(PATH):
full_path_fnames = map(lambda fn: os.path.join(dirpath, fn),
filenames)
full_path_fnames = filter(is_valid_file, full_path_fnames)
pool.map(readFile, full_path_fnames)
if __name__ == '__main__':
sys.exit(main())
【问题讨论】:
-
也许eric.lubow.org/2009/python/… 对你有用。
标签: python connection-pooling mysql-python