dongluo3962 2010-04-22 20:30
浏览 55
已采纳

如何使用pdo而不是大型数组从数据库中获取可迭代结果集?

I'm using PDO inside a database abstraction library function query that I've made.

I'm using fetchAll(), which if you have a lot of results, is supposed to get memory intensive, so I want to provide an argument to toggle between a fetchAll associative array and a pdo result set that can be iterated over with foreach and requires less memory (somehow).

I remember hearing about this, and I searched through the PDO docs, but I couldn't find any useful way to do that.

Does anyone know how to get an iterable resultset back from PDO instead of just a flat array? And am I right that using an iterable resultset will be easier on memory?

I'm using Postgresql, if it matters in this case.

.

.

.

The current query function is as follows, just for clarity.

/**
 * Running bound queries on the database.
 *
 * Use: query('select all from players limit :count', array('count'=>10));
 * Or: query('select all from players limit :count', array('count'=>array(10, PDO::PARAM_INT)));
**/
function query($sql_query, $bindings=array()){
 DatabaseConnection::getInstance();
 $statement = DatabaseConnection::$pdo->prepare($sql_query);
 foreach($bindings as $binding => $value){
  if(is_array($value)){
   $statement->bindParam($binding, $value[0], $value[1]);
  } else {
   $statement->bindValue($binding, $value);
  }
 }
 $statement->execute();
 // TODO: Return an iterable resultset here, and allow switching between array and iterable resultset.
 return $statement->fetchAll(PDO::FETCH_ASSOC); 
}
  • 写回答

1条回答 默认 最新

  • douxiaomang5640 2010-04-22 21:43
    关注

    Looks like I've found my solution in the form of the PDOStatement object itself, i.e. after doing a $statement->execute(); You can simply pass along the $statement object and foreach over that object. Can't use it as an array, but can do just about everything else with it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题