others - PHP - 使用PDO::exec和PDO::query时,PDO::ATTR_PERSISTENT=true是否有区别?

PDO::exec和PDO::query在有PDO::ATTR_PERSISTENT =true时有区别,当使用PDO::exec连接时将不会被重用,并且最终导致MySQL出现"to many connections"错误,因为它们没有关闭(或者重复使用)。

请参见以下代码段示例:


<?php



$pdo_attr = [


 PDO::ATTR_PERSISTENT => true,


];



$pdo = new PDO("mysql:host=mysql;dbname=empty","root","iamreallysecure", $pdo_attr);



// The following will give a to many connections error after a few browser refreshes (connection limit is set to 10)


var_dump($pdo->exec("SELECT 1"));



// While the following does NOT leave >10 connections open and continues to work


//var_dump($pdo->query("SELECT 1")->fetchAll());



在这种情况下,exec和query有什么区别?

时间: 作者:

如果使用exec()用于SELECT,那么你已经做错了,此函数(如手册中所述)不从数据库获取结果,它只能用于不产生结果集,且没有变量输入的查询。


$options = [


 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION


];


$pdo = new PDO("mysql:host=localhost;dbname=test;port=3307","root","", $options);



// The following will give:


// SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.


var_dump($pdo->exec("SELECT 1"));


var_dump($pdo->exec("SELECT 1"));



PDOException : SQLSTATE [HY000] : General error : 2014 cannot execute queries while other unbuffered queries are active. 考虑使用PDOStatement::fetchAll(),或者,如果代码只针对mysql运行,可以通过设置PDO::MYSQL_ATTR_USE_BUFFERED_QUERY属性启用查询缓冲。

在使用持久连接时使用exec()和query()是有区别的,但在不使用持久连接时也存在这种区别,

作者:
...