当我尝试使用MySQLdb通过Python脚本从MySQL表中获取1,5百万行时,我的服务器上收到“内存不足”错误。
调试后,我得到了此信息。
使用SSCoursor或默认光标,它仅使用650 MB RAM
使用SSDictCursor会使用超过2.5 GB的RAM,并导致“内存不足”错误
那正常吗???如果否,那么如何减少SSDictCursor的内存使用量?
Python版本2.7.12
try:
print "About to connect to db."
host = '127.0.0.1'
port = int(conf['sshtunnel']['fwdport'])
if rs_env == 'private':
host = conf['db'][data_src]['private']['dbhost']
port = 3306
db = MySQLdb.connect(
host = host,
port = port,
user = conf['db'][data_src][rs_env]['dbuser'],
passwd = conf['db'][data_src][rs_env]['dbpass'],
db = conf['db'][data_src]['db'],
# cursorclass = MySQLdb.cursors.SSCursor)
# use ssdictcursore for fetch rows in server side without out of memory error
cursorclass = MySQLdb.cursors.SSDictCursor)
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)
c = db.cursor()
query = "SELECT * FROM ....."
c.execute(query)
print "\n EXECUTED"
# fetch rows one by one for prevent outh of memory error
results = []
while True:
row = c.fetchone()
if row == None:
break
results.append(row)
print "Fetched {0} records from DB.".format(str(len(results)))
c.close()
db.close()