当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL中预处理语句prepare、execute与deallocate的使用教程

MySQL中预处理语句prepare、execute与deallocate的使用教程

2017年12月07日  | 移动技术网IT编程  | 我要评论

碧血神雕鹿鼎记,天邪吟,苏宁电器积分查询

前言

mysql官方将prepare、execute、deallocate统称为prepare statement,我习惯称其为【预处理语句】,其用法十分简单,下面话不多说,来一起看看详细的介绍吧。

示例代码

prepare stmt_name from preparable_stmt

execute stmt_name
 [using @var_name [, @var_name] ...] -

{deallocate | drop} prepare stmt_name

举个栗子:

mysql> prepare pr1 from 'select ?+?';
query ok, 0 rows affected (0.01 sec)
statement prepared

mysql> set @a=1, @b=10 ;
query ok, 0 rows affected (0.00 sec)

mysql> execute pr1 using @a, @b;
+------+
| ?+? |
+------+
| 11 |
+------+
1 row in set (0.00 sec)

mysql> execute pr1 using 1, 2; -- 只能使用用户变量传递。
error 1064 (42000): you have an error in your sql syntax; check the manual that corresponds to your mysql server version for the 
right syntax to use near '1, 2' at line 1

mysql> deallocate prepare pr1;
query ok, 0 rows affected (0.00 sec)

使用parepare statement可以减少每次执行sql的语法分析,比如用于执行带有where条件的select和delete,或者update,或者insert,只需要每次修改变量值即可。

同样可以防止sql注入,参数值可以包含转义符和定界符。

适用在应用程序中,或者sql脚本中均可。

更多用法:

同样prepare ... from可以直接接用户变量:

mysql> create table a (a int);
query ok, 0 rows affected (0.26 sec)

mysql> insert into a select 1;
query ok, 1 row affected (0.04 sec)
records: 1 duplicates: 0 warnings: 0

mysql> insert into a select 2;
query ok, 1 row affected (0.04 sec)
records: 1 duplicates: 0 warnings: 0

mysql> insert into a select 3;
query ok, 1 row affected (0.04 sec)
records: 1 duplicates: 0 warnings: 0

mysql> set @select_test = concat('select * from ', @table_name);
query ok, 0 rows affected (0.00 sec)

mysql> set @table_name = 'a';
query ok, 0 rows affected (0.00 sec)

mysql> prepare pr2 from @select_test;
query ok, 0 rows affected (0.00 sec)
statement prepared

mysql> execute pr2 ;
+------+
| a |
+------+
| 1 |
| 2 |
| 3 |
+------+
3 rows in set (0.00 sec)

mysql> drop prepare pr2; -- 此处drop可以替代deallocate
query ok, 0 rows affected (0.00 sec)

每一次执行完execute时,养成好习惯,须执行deallocate prepare … 语句,这样可以释放执行中使用的所有数据库资源(如游标)。

不仅如此,如果一个session的预处理语句过多,可能会达到max_prepared_stmt_count的上限值。

预处理语句只能在创建者的会话中可以使用,其他会话是无法使用的。

而且在任意方式(正常或非正常)退出会话时,之前定义好的预处理语句将不复存在。

如果在存储过程中使用,如果不在过程中deallocate掉,在存储过程结束之后,该预处理语句仍然会有效。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网