MySQLi为什么要准备语句? [英] why MySQLi prepared statements?

查看:52
本文介绍了MySQLi为什么要准备语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MySQLi中使用预处理语句有什么优势?

What are the advantages of using prepared statements with MySQLi?

如果唯一的目的是保护查询,那么使用mysqli_real_escape_string之类的查询来清理查询不是更好,而不是为每个查询编写那么多的代码行(例如prepare,bind_param,execute,close等). )?

If the only purpose is to secure the query, isn't it better to clean the query using something like mysqli_real_escape_string instead of writing so many lines of code for each query (like prepare, bind_param, execute, close etc.)?

推荐答案

准备语句不仅仅是为了代码安全.它可以帮助SQL Server解析您的语句并为查询生成执行计划.

Preparing statements is not just for code security. It helps the SQL server parse your statement and generate an execution plan for your query.

如果您运行SELECT 1000次,则SQL Server将必须解析,准备并生成有关如何获取1000次数据的计划.

If you run a SELECT 1000 times then the SQL server will have to parse, prepare, and generate a plan on how to get your data 1000 times.

如果准备一条语句,然后以不同的绑定值运行准备好的语句1000次,则该语句仅被解析一次,并且每次都使用相同的查询计划.

If you prepare a statement then run the prepared statement 1,000 times each with different bound values then the statement is parsed only once and the same query plan is used each time.

这不仅在您在脚本内运行1,000个查询时有帮助,而且在您只有1条语句并运行1000次脚本时也有帮助.服务器可以记住计划服务器端.下次您的脚本运行时,它将再次使用相同的计划.

This helps not only when you run 1,000 queries inside the script but also if you only have 1 statement and run the script 1,000 times. The server can remember the plan server side. The next time your script runs it will use the same plan again.

当然,对于一个或两个查询来说,这似乎微不足道,但是当您开始执行大量查询或重复执行相同的查询时,您将节省大量的处理时间.

Sure it may seem trivial for one or two queries but when you start executing large numbers of queries or the same query repeatedly you will save a lot of processing time.

这篇关于MySQLi为什么要准备语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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