mysql_unbuffered_query() 向 MySQL 发 送一条 SQL 查询 query,但不像 mysql_query() 那样自动获取并缓存结果集。一方面,这在处理很大的结果集时会节省可观的内存。 另一方面,可以在获取第一行后立即对结果集进行操作,而不用等到整个 SQL 语句都执行完毕。当使用多个数据库连接时,必须指定可选参 数 link_identifier。
注意: mysql_unbuffered_query() 的好处是有代价的: 在 mysql_unbuffered_query() 返回的结果集之上不能使 用 mysql_num_rows() 和 mysql_data_seek()。此外在向 MySQL 发送一条新的 SQL 查询之前,必须提取掉所 有未缓存的 SQL 查询所产生的结果行。
看代码测试:(注:表S20120726是一个将近400M的数据表, 而且数据库和php程序都在一台机器上)
1.test_mysql_query.php
<?php $conn = mysql_connect('localhost', 'root', ''); mysql_select_db('qxt_summary', $conn); $starttime = array_sum(explode(' ', microtime())); $res = mysql_query("select * from S20120726"); //数据量非常大 echo "Mysql_query Cost: " . durtime($starttime) . " seconds\n"; $row = mysql_fetch_array($res); echo "Mysql_fetch_array Cost: " . durtime($starttime) . " seconds\n"; mysql_close($conn); echo "Mysql_close Cost: " . durtime($starttime) . " seconds\n"; function durTime(&$starttime){ $temp = $starttime; $starttime = array_sum(explode(' ', microtime())); return ($starttime - $temp); } ?>
运行结果:
[***@test PHP]$ php test_mysql_query.php
Mysql_query Cost: 12.175949811935 seconds
Mysql_fetch_array Cost: 0.00018310546875 seconds
Mysql_close Cost: 0.00016689300537109 seconds
而且在程序运行时,通过top查看进程内存状态,此时内存也用掉300多M
2.test_mysql_unbuffered_query.php
<?php $conn = mysql_connect('localhost', 'root', ''); mysql_select_db('qxt_summary', $conn); $starttime = array_sum(explode(' ', microtime())); $res = mysql_unbuffered_query("select * from S20120726"); //数据量非常大 echo "Mysql_unbuffered_query Cost: " . durtime($starttime) . " seconds\n"; $row = mysql_fetch_array($res); echo "Mysql_fetch_array Cost: " . durtime($starttime) . " seconds\n";mysql_close($conn); echo "Mysql_close Cost: " . durtime($starttime) . " seconds\n"; function durTime(&$starttime){ $temp = $starttime; $starttime = array_sum(explode(' ', microtime())); return ($starttime - $temp); } ?>
[****@test PHP]$ php test_mysql_unbuffered_query.php
Mysql_unbuffered_query Cost: 0.0081520080566406 seconds
Mysql_fetch_array Cost: 0.00020217895507812 seconds
Mysql_close Cost: 13.506908893585 seconds
用top查看内存变化,内存只用了一点。
通过时间可以发现两个程序用的时间差不多, 一个在mysql_query()上花费了很多时间, 一个在mysql_close()上花费了很多时间, 本人觉得这个时间是跟缓冲区接收mysql的数据所用时间相关,只有数据接收完毕之后,才可以关闭mysql连接,这也就是mysql_unbuffered_query之后,马上关闭连接,需要花费很长的时间,当然mysql_unbuffered_query有很大的优势,可以根据实际需求选择。