PDO:循环调用prepare()的成本吗? [英] PDO: Cost of Calling prepare() in a loop?

查看:89
本文介绍了PDO:循环调用prepare()的成本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的网站编写一个数据库类,其中包含诸如fetchOnefetchAll之类的函数,这些函数准备,执行(+绑定)并全部获取查询,因此我不必单独调用那些每次都起作用.我网站上的某些cron作业在一个循环中执行了数千甚至上百万个查询.

I'm writing a database class for my website with functions such as fetchOne, fetchAll which prepare, execute (+ bind), and fetch the query all in one so I don't have to individually call those functions every time. Some cron jobs on my site execute thousands, or even millions of queries inside of a loop.

使用我的类会导致在每次循环迭代时重新准备该语句,还是PDO记住"查询已经准备好了?这是否会对性能产生重大影响?如果可以,解决方案是仅提供一个传递数据库实例的功能,并在循环外执行类似$db->getDb()->prepare($query);的功能?还是有更好的解决方案?

Would using my class cause the statement to be re-prepared each iteration of the loop or would PDO "remember" the query has already been prepared? Would this significantly impact performance and if so could the solution be to just provide a function that passes the database instance and do something like $db->getDb()->prepare($query); outside of the loop? Or is there a better solution?

示例功能:

public function fetchOne($query, $params = array(), $fetchMode = PDO::FETCH_ASSOC)
{
    $stmt = self::prepareExecute($query, $params);

    $result = $stmt->fetch($fetchMode);
    if (count($result) < 1)
        $result = FALSE;

    $stmt->closeCursor();
    unset($stmt);
    return($result);
}

推荐答案

您不希望多次重新准备"相同的查询.这是prepare语句的目的.您只需准备一次,绑定变量,然后只需切换变量的值并重新执行循环的每次迭代即可.

you would not want to "re-prepare" the same query multiple times. this is the purpose of the prepare statement. you prepare it once, bind the variable(s), then you simply switch the variables' values and re-execute each iteration of the loop.

http://www.php.net/manual/en/pdostatement. bindparam.php

以这种方式进行操作将大大提高您的性能,而不是其他方法.

doing it this way will greatly increase your performance over alternative methods.

这篇关于PDO:循环调用prepare()的成本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆