python mysql execute()非常慢

时间:2013-01-08 21:56:48

标签: python mysql

我在应用程序中找到了mysql的execute()函数的缓慢。我精心设计了一个简单的SQL查询来举例说明这个问题:

SELECT * FROM `cid444_agg_big` c WHERE 1

>>> import MySQLdb as mdb
>>> import time;
>>> 
>>> dbconn =  mdb.connect('localhost','*****','*****','*****');
>>> cursorconn = dbconn.cursor()
>>> 
>>> sql="SELECT * FROM `cid444_agg_big` c WHERE 1";
>>> 
>>> startstart=time.time();
>>> cursorconn.execute(sql);
21600L #returned 21600 records
>>> print time.time()-startstart, "for execute()"
2.86254501343 for execute() #why does this take so long?
>>> 
>>> startstart=time.time();
>>> rows = cursorconn.fetchall()
>>> print time.time()-startstart, "for fetchall()"
0.0021288394928 for fetchall() #this is very fast, no problem with fetchall()

在mysql shell中运行此查询,产生0.27秒,或者快10倍!!!

我唯一想到的是返回数据的大小。这将返回21600“宽”行。所以很多数据都被发送到python。数据库是localhost,因此没有网络延迟。

为什么这需要这么长时间?

更新更多信息

我在php中写了一个类似的脚本:

$c = mysql_connect ( 'localhost', '*****', '****', true );
mysql_select_db ( 'cachedata', $c );

$time_start = microtime_float();
$sql="SELECT * FROM `cid444_agg_big` c WHERE 1";
$q=mysql_query($sql);$c=0;
while($r=mysql_fetch_array($q))
$c++;//do something?
echo "Did ".$c." loops in ".(microtime_float() - $time_start)." seconds\n";


function microtime_float(){//function taken from php.net
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec + (float)$sec);
}

打印:

Did 21600 loops in 0.56120800971985 seconds

这会循环播放所有数据,而不是一次性全部检索。 PHP似乎比python版本 6倍 ....

1 个答案:

答案 0 :(得分:2)

The default MySQLdb cursorexecute上将完整的结果集提取到客户端,而fetchall()只会将数据从内存中复制到内存中。

如果要将结果集存储在服务器上并按需获取,则应使用SSCursor代替。

  

Cursor:
  这是标准的Cursor类,它将行作为元组返回,并将结果集存储在客户端中。

     

SSCursor:
  这是一个Cursor类,它将行作为元组返回,并将结果集存储在服务器中。

相关问题