小标
2019-01-04
来源 :
阅读 1755
评论 0
摘要:本文主要向大家介绍了MySQL数据库之MySQL Prepared Statement ,通过具体的内容向大家展现,希望对大家学习MySQL数据库有所帮助。
本文主要向大家介绍了MySQL数据库之MySQL Prepared Statement ,通过具体的内容向大家展现,希望对大家学习MySQL数据库有所帮助。
Summary: in this tutorial, you will learn how to use MySQL prepared statement to make your queries execute faster and more secure.
Introduction to MySQL Prepared Statement
Prior MySQL version 4.1, the query is sent to the MySQL server in the textual format. In turn, MySQL returns the data to the client using textual protocol. MySQL has to parse the query fully and coverts the result set into a string before returning it to the client.
The textual protocol has serious performance implication. To resolve this problem, MySQL added a new feature called prepared statement since version 4.1.
The prepared statement takes advantage of client/server binary protocol. It passes query that contains placeholders (?) to the MySQL server as the following example:
SELECT * FROM products WHERE productCode = ?
When MySQL executes this query with different productcode values, it does not have to parse the query fully. As a result, this helps MySQL execute the query faster, especially when MySQL executes the query multiple times. Because the prepared statement uses placeholders (?), this helps avoid many variants of SQL injection hence make your application more secure.
MySQL prepared statement usage
In order to use MySQL prepared statement, you need to use other three MySQL statements as follows:
PREPARE – Prepares statement for execution.
EXECUTE – Executes a prepared statement preparing by a PREPARE statement.
DEALLOCATE PREPARE – Releases a prepared statement.
The following diagram illustrates how to use the prepared statement:
MySQL prepared statement example
Let’s take a look at an example of using the MySQL prepared statement.
PREPARE stmt1 FROM 'SELECT productCode, productName FROM products WHERE productCode = ?'; SET @pc = 'S10_1678'; EXECUTE stmt1 USING @pc; DEALLOCATE PREPARE stmt1;
First we used the PREPARE statement to prepare a statement for execution. We used the SELECT statement to query product data from the products table based on a specified product code. We used question mark (?) as a placeholder for the product code.
Next, we declared a product code variable @pc and set it values to S10_1678.
Then, we used the EXECUTE statement to execute the prepared statement with product code variable @pc.
Finally, we used the DEALLOCATE PREPARE to release the prepared statement.
In this tutorial, we have shown you how to use MySQL prepared statement to execute a query with placeholders to improve the speed of the query and make your query more secure.
本文由职坐标整理并发布,希望对同学们学习MySQL有所帮助,更多内容请关注职坐标数据库MySQL数据库频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号