PHP使用Mysqli的prepare语句有什么好处?
时间:2021-07-01 10:21:17
帮助过:18人阅读
回复内容:
《High Performance MySQL》 一书的 225 -228 页。讲的非常详细,我简单整理下:
好处:
(1) Parse the query only once
(2) Perform some query optimization steps only once
(3) Sending parameters via the binary protocol is more efficient than sending them as ASCII text
比如 DATE,对于 Prepare 之后,发送 Date 只用 3 Bytes;如果没有 Prepare, DATE 必须以 String 的形式发送,需要数据库方再解析,这样需要发送 10 Bytes。
(4) Only the parameters (not the entire query text) need to be sent for each execution
(5) MySQL stores the parameteres directly into buffers on the server
(6) Also helps with security, there is no need to escape or quote values.
坏处:
(1) Local to a connection, so another connection cannot re-use
(2) Cannot use MySQL query cache (5.1 版本之前)
(3) Not always more efficient, if you use it only once
(4) Cannot use inside a stored function (Stored procedure 是可以的)
(5) May lead to "leak" if you forget to deallocate it
基本上直接打原文,部分地方稍微做了下改变,以及适当的地方加了补充。
1:安全方面,sql注入这类问题
2:传输体积优化[参数传递]
3:避免重复解析,
mysql是非持继连接函数而mysqli是永远连接函数。
也就是说mysql每次链接都会打开一个连接的进程而mysqli多次运行mysqli将使用同一连接进程,从而减少了服务器的开销