博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
解决mysqldb查询大量数据导致内存使用过高的问题
阅读量:6272 次
发布时间:2019-06-22

本文共 2048 字,大约阅读时间需要 6 分钟。

1.源码
connection=MySQLdb.connect(    host="thehost",user="theuser",    passwd="thepassword",db="thedb")cursor=connection.cursor()cursor.execute(query)for row in cursor.fetchall():    print(row)
2.问题
普通的操作不管是fetchall()还是fetchone()都是先将数据加载到本地再进行计算,大量的数据会导致内存资源消耗光。解决的方法是使用SSCurosr光标来处理。
3.优化后的代码  
import MySQLdb.cursorsconnection=MySQLdb.connect(    host="thehost",user="theuser",    passwd="thepassword",db="thedb",    cursorclass = MySQLdb.cursors.SSCursor)cursor=connection.cursor()cursor.execute(query)for row in cursor:    print(row)
參考文档:http://mysql-python.sourceforge.net/MySQLdb.html#
关键段落截取:
BaseCursor
The base class for Cursor objects. This does not raise Warnings.
CursorStoreResultMixIn
Causes the Cursor to use the 
mysql_store_result() function to get the query result. The entire result set is stored on the client side.
CursorUseResultMixIn
Causes the cursor to use the 
mysql_use_result() function to get the query result. The result set is stored on the server side and is transferred row by row using fetch operations.
CursorTupleRowsMixIn
Causes the cursor to return rows as a tuple of the column values.

CursorDictRowsMixIn

Causes the cursor to return rows as a dictionary, where the keys are column names and the values are column values. Note that if the column names are not unique, i.e., you are selecting from two tables that share column names, some of them will be rewritten as 
table.column. This can be avoided by using the SQL 
ASkeyword. (This is yet-another reason not to use 
* in SQL queries, particularly where 
JOIN is involved.)
Cursor
The default cursor class. This class is composed of 
CursorWarningMixIn
CursorStoreResultMixIn
CursorTupleRowsMixIn, and 
BaseCursor, i.e. it raises 
Warning, uses
mysql_store_result(), and returns rows as tuples.
DictCursor
Like 
Cursor except it returns rows as dictionaries.
SSCursor
A "server-side" cursor. Like 
Cursor but uses 
CursorUseResultMixIn. Use only if you are dealing with potentially large result sets.
SSDictCursor
Like 
SSCursor except it returns rows as dictionaries.

转载地址:http://wtlpa.baihongyu.com/

你可能感兴趣的文章
linux下libevent安装
查看>>
用ip来获得用户所在地区信息
查看>>
卡尔曼滤波
查看>>
linux下面覆盖文件,如何实现直接覆盖,不提示
查看>>
CSS3阴影 box-shadow的使用和技巧总结
查看>>
Linux下高cpu解决方案
查看>>
SQL事务用法begin tran,commit tran和rollback tran的用法
查看>>
centos7 crontab笔记
查看>>
.Net AppDomain.CurrentDomain.AppendPrivatePath(@"Libs");
查看>>
【Unity3D基础教程】给初学者看的Unity教程(零):如何学习Unity3D
查看>>
Android Mina框架的学习笔记
查看>>
合并两个排序的链表
查看>>
rtf格式的一些说明,转载的
查看>>
REST Security with JWT using Java and Spring Security
查看>>
echarts学习总结(二):一个页面存在多个echarts图形,图形自适应窗口大小
查看>>
IIS7显示ASP的详细错误信息到浏览器
查看>>
使用fiddler对手机APP进行抓包
查看>>
exit和_exit的区别
查看>>
Javascript、Jquery获取浏览器和屏幕各种高度宽度(单位都为px)
查看>>
php不重新编译,安装未安装过的扩展,如curl扩展
查看>>