使用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 ; +------+ (北联网教程,专业提供视频软件下载)
……