MySQL prepare语法:
PREPARE statement_name FROM preparable_SQL_statement; /*定义*/
EXECUTE statement_name [USING @var_name [, @var_name] ...]; /*执行预处理语句*/
{DEALLOCATE | DROP} PREPARE statement_name /*删除定义*/ ;
PREPARE语句用于预备一个语句,并指定名称statement_name,以后引用该语句。语句名称对大小写不敏感。preparable_stmt可以是一个文字字符串,也可以是一个包含了语句文本的用户变量。该文本必须表现为一个单一的SQL语句,而不是多个语句。在这语句里,‘?’字符可以被用于标识参数,当执行时,以指示数据值绑定到查询后。‘?’字符不应加引号,即使你想要把它们与字符串值结合在一起。参数标记只能用于数据值应该出现的地方,而不是SQL关键字,标识符,等等。
如果预语句已经存在,则在新的预语句被定义前,它会被隐含地删掉。
例如:
mysql> prepare optimize_tables from "optimize table temp";
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute optimize_tables;
+-----------+----------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+-----------+----------+----------+----------+
| test.temp | optimize | status | OK |
+-----------+----------+----------+----------+
1 row in set (0.37 sec)
mysql> deallocate prepare optimize_tables;
Query OK, 0 rows affected (0.00 sec)
--------------------------------------------------------------------------
mysql> prepare md5sum from 'select md5(?) AS md5sum';
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> set @a=111;
Query OK, 0 rows affected (0.00 sec)
mysql> set @b=222;
Query OK, 0 rows affected (0.00 sec)
mysql> execute md5sum using @a;
+----------------------------------+
| md5sum |
+----------------------------------+
| 698d51a19d8a121ce581499d7b701668 |
+----------------------------------+
1 row in set (0.00 sec)
mysql> execute md5sum using @b;
+----------------------------------+
| md5sum |
+----------------------------------+
| bcbe3365e6ac95ea2c0343a2395834dd |
+----------------------------------+
1 row in set (0.00 sec)
mysql> drop prepare md5sum;
Query OK, 0 rows affected (0.00 sec)
--------------------------------------------------------------------------------------
mysql> prepare update_table from "update users set password=password('aaa') where username='a'";
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute update_table;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
mysql> deallocate prepare update_table;
Query OK, 0 rows affected (0.00 sec)