mysql prepare例子_MySQL中预处理语句prepare、execute与deallocate的使用教程

前言

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掉,在存储过程结束之后,该预处理语句仍然会有效。

总结

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

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值