PDO 绑定值与插入
除了在 PDO 中使用绑定值时转义值的优点之外,使用具有多个值的绑定值(准备一次语句,但使用不同的值执行多次)而不是像这样的单个插入语句时,性能是否有任何差异 INSERT INTO table_name VALUES (value1, value2, value3),(value1, value2, value3),(value1, value2, value3)
Besides the advantage of escaping value when using bind value in PDO, is there any difference in performance when using bind value with multiple values (prepare the statement once, but execute multiple time with different values) instead of a single insert statement likeINSERT INTO table_name VALUES (value1, value2, value3),(value1, value2, value3),(value1, value2, value3)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我自己对 100,000 条记录进行了一些测试。对于更简单的场景,我没有使用 INSERT INTO 而是 REPLACE INTO 以避免每次都必须拿出新的密钥。
REPLACE INTO
原始替换为 3 列示例
REPLACE INTO table_name VALUES (value1, value2, value3),(value1, value2, value3),(value1, value2, value3)......
处理 100,000 行大约需要 14 秒。NORMAL BIND
使用准备语句、绑定值并执行准备好的语句大约需要 33 秒
BIND BUT 1 EXECUTE
在准备之前创建一个长语句,绑定所有参数并执行一次大约需要 >22 秒
请注意,这些是粗略数字,用于在 100,000 条记录上创建 REPLACE INTO(删除和插入的字段)。
Did some tests myself on 100,000 records. For a simpler scenario I did not use INSERT INTO but REPLACE INTO to avoid having to come up with new keys every time.
REPLACE INTO
A raw replace into of 3 columns example
REPLACE INTO table_name VALUES (value1, value2, value3),(value1, value2, value3),(value1, value2, value3)......
on 100,000 rows took approx 14sec.NORMAL BIND
Using a preparing the statement, binding the value and executing the prepared statement took around 33 seconds
BIND BUT 1 EXECUTE
Creating a long statement before preparing it, binding all the paramaters and executing once took around 22 seconds
Note that these are rough numbers and used creating REPLACE INTO (where fields where deleted and insert) on 100,000 records.
如果使用准备好的语句,速度会更快(对于 MySQL)。这样,实际的 SQL 被解析一次,数据被发送多次 - 因此,用于转换 INSERT INTO ... 的实际 SQL 层不会在每次您想要执行该特定插入时调用,它仅被解析一次,然后您只需发送您想要插入(或执行任何其他操作)的不同参数(不同数据)。
因此,它不仅减少了开销,还提高了安全性(如果您使用 PDO::bindValue/param ,因为基于所使用的驱动程序/字符集进行了正确的转义)。
简而言之 - 是的,您的插入将会更快、更安全。但到底是多少——很难说。
It's faster (for MySQL) if you use prepared statements. That way, the actual SQL is parsed once and data is sent multiple times - so the actual SQL layer for transforming your INSERT INTO ... isn't invoked every time you want to execute that particular insert, it's parsed only once and then you just send different parameters (different data) that you want to insert (or execute any other operation).
So not only does it reduce overhead, it increases security as well (if you use PDO::bindValue/param due to proper escaping based on driver / charset being used).
In short - yes, your insert will be faster and safer. But by what margin - it's hard to tell.