在python中使用MySQLdb向数据库插入新元素时内存泄漏
我有一个包含图像列表的文件夹,我从中创建每个图像的散列,并使用python中的MySQLdb将其逐个插入sql数据库。该文件夹中大约有1400个图像,我需要将其散列存储在该数据库中。但是,每次插入都会消耗我的部分可用RAM,最终导致0个可用RAM空间,进程被终止。我不明白为什么会发生这种情况,因为一次简单的插入不应该导致将整个数据库放入RAM中。因此,插入时消耗的RAM量不应取决于数据库的大小。然而,我的RAM被时间填满了,即使每次插入后我都在执行self.db.close()。为什么会发生这种情况,我该如何解决 代码如下:在python中使用MySQLdb向数据库插入新元素时内存泄漏,python,mysql,memory-leaks,mysql-python,Python,Mysql,Memory Leaks,Mysql Python,我有一个包含图像列表的文件夹,我从中创建每个图像的散列,并使用python中的MySQLdb将其逐个插入sql数据库。该文件夹中大约有1400个图像,我需要将其散列存储在该数据库中。但是,每次插入都会消耗我的部分可用RAM,最终导致0个可用RAM空间,进程被终止。我不明白为什么会发生这种情况,因为一次简单的插入不应该导致将整个数据库放入RAM中。因此,插入时消耗的RAM量不应取决于数据库的大小。然而,我的RAM被时间填满了,即使每次插入后我都在执行self.db.close()。为什么会发生这种
def create_hash(userpath, hashfunc=imagehash.phash):
print "here"
image_filenames = [os.path.join(userpath, path)
for path in os.listdir(userpath) if is_image(path)]
for img in sorted(image_filenames):
try:
hash_img = hashfunc(Image.open(img))
img_url = img.split("/")[-1]
print hash_img
c = Connection()
c.insert(img_url, hash_img)
c.close_connection()
except Exception,e:
print str(e)
下面是Connection类的insert函数:
class Connection():
def __init__(self):
self.db = MySQLdb.connect("localhost","root","password","some_schema")
self.cursor = self.db.cursor()
def insert(self, image_url, hash_value):
query = "insert into image_hash (image_url, hash) value (\"%s\",\"%s\")"%(image_url, hash_value)
print query
try:
self.cursor.execute(query)
self.db.commit()
except Exception,e:
self.db.rollback()
print str(e)
def close_connection(self):
self.db.close()
请注意,我在上面的代码中使用了尝试在一个查询中插入多行 使用VALUES语法的INSERT语句可以插入多行。到 为此,请包含多个列值列表,每个列值都包含在 括号和之间用逗号分隔 看,内存还在泄漏
class Connection():
def __init__(self):
self.db = MySQLdb.connect("localhost","root","password","some_schema")
self.cursor = self.db.cursor()
def insert(self, values):
query = "insert into image_hash (image_url, hash) values {0}".format(values)
try:
self.cursor.execute(query)
self.db.commit()
except Exception,e:
self.db.rollback()
print str(e)
def close_connection(self):
self.db.close()
def create_hash(userpath, hashfunc=imagehash.phash):
_join = os.path.join
image_filenames = [_join(userpath, path)
for path in os.listdir(userpath) if is_image(path)]
hash_list = []
for img in sorted(image_filenames):
try:
hash_img = hashfunc(Image.open(img))
img_url = img.split("/")[-1]
hash_list.append("('{0}', '{1}')".format(img_url, hash_img))
except Exception,e:
print str(e)
c = Connection()
c.insert(', '.join(hash_list))
c.close_connection()
极不可能与mysql有任何关系。更可能与您的哈希有关。请发布一些代码,然后添加代码,这样我们就可以看到是什么导致了添加的代码。你能看看是什么导致了这个问题吗?我刚刚检查了ImageHash库,我发现它是一个18MB的下载,如果泄漏在里面,我一点也不会感到惊讶。注释掉create_hash函数中处理DB的三行代码,然后再次运行它,你会看到它崩溃了。它确实吓坏了。我想把for循环从python脚本中去掉,这样,这个新的python脚本只为一个文件创建哈希。然后在一个shell脚本中创建一个for循环,该脚本会对这1400个文件中的每个文件一次又一次地调用python脚本。这有意义吗?因为,通过这样做,我创建了一个python进程,创建并向数据库中添加图像哈希,然后终止该进程,从而再次释放RAM,这样做了1400次。这有帮助吗?没有解决问题。RAM会像以前一样耗尽,当空闲RAM变为零时,进程会被终止,甚至在控件退出for循环之前,这种情况就已经发生了。我猜将这1400个哈希添加到哈希列表中会占用所有RAM