PDO::exec() 还是 PDO::query()?
我曾经将此作为传递给 PDO 构造函数的选项之一(第 4 个参数):
$aOptions[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES utf8";
但刚刚发现由于某些错误,它在 Windows 上的某些 php 版本上不起作用(在 5.3 中不起作用)。
现在我需要使用 $pdo->exec("SET NAMES utf8");
或 $pdo->query(" 运行
SET NAMES utf8
SET NAMES utf8");
在实例化 pdo 对象之后。那么,我应该使用哪一个 - exec() 还是 query()?
I used to have this as one of the options (4th param) passed to PDO constructor:
$aOptions[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES utf8";
But just found that it does not work on certain php versions on Windows (does not work in 5.3) due to some bug.
Now I need to run SET NAMES utf8
using either $pdo->exec("SET NAMES utf8");
or $pdo->query("SET NAMES utf8");
right after the instantiating the pdo object. So, which one should I use - exec() or query()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
PDO::EXEC
时,返回的结果不是PDOStatement
的结果,而是受影响行的整数。使用
PDO::QUERY
时,返回的结果是PDOStatement
。所以答案是这取决于您需要对数据执行什么操作,如果您需要运行查询而不对结果执行任何操作,那么您应该使用
exec
来执行查询,否则如果您需要行数,返回的数据应该使用pdo::query
,然后使用调用返回的结果。关于该错误,有几种解决方法,您可以采取
PDO_MYSQL
MYSQL_ATTR_INIT_COMMAND
替换为1002
第二个问题可能在 64 位操作系统和某些 Windows 配置上存在一些问题。
错误信息:http://bugs.php.net/bug.php?id=47224< /a>
When using
PDO::EXEC
the result returned is not of anPDOStatement
but an integer of the rows affected.When using
PDO::QUERY
the result returned is aPDOStatement
.So the answer is it depends on what you need to do with the data, if you need to run query and not do anything with the results, then you should use
exec
to execute the query, otherwise if you need the number of rows, the data returned you should usepdo::query
and then use the results returned by the call.in regards to the bug there are several work around that you can take
PDO_MYSQL
MYSQL_ATTR_INIT_COMMAND
with1002
the second issue may have some issues on 64bit's OS's and Some windows configurations.
Bug Information: http://bugs.php.net/bug.php?id=47224
PDO::exec() 应用于不返回结果集的查询,例如删除语句或“set”。当您期望返回结果集时,应使用 PDO::query()。它返回一个 PDOStatement 对象给您,您可以迭代该对象来获取各个行。但请注意,如果您在查询中使用来自不受信任来源的数据,则准备好的语句将是执行任一类型查询的最佳方法(但您可能知道这一点)。
所以,在你的情况下 PDO::exec() 是正确的。您确定将设置名称命令作为最后一个值传递给 PDO::__construct() 不起作用吗?它对我有用,我在 Windows 上有 PHP 5.3。您能否发布更多您正在做的事情的示例代码?
PDO::exec() should be used for queries that do not return a resultset, such as a delete statement or 'set'. PDO::query() should be used when you expect a resultset to be returned. It returns a PDOStatement object to you that you can iterate over to get the individual rows. Note though that if you're using data from an untrusted source in your queries prepared statements would be the best way to go for either kind of query (but you probably knew that).
So, in your case PDO::exec() would be right. Are you sure though that passing the set names command to PDO::__construct() as the last value doesn't work? It works for me and I have PHP 5.3 on Windows. Could you post some more sample code of what you're doing?