首页 > 数据库 > MySQL > 正文

MySQL prepare语句的SQL语法

2024-07-24 12:49:24
字体:
来源:转载
供稿:网友
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关键字,标识符,等等。
如果预语句已经存在,则在新的预语句被定义前,它会被隐含地删掉。

每次都看别人的,今天我自己写下来,以后就不用看别人的了
语法
PREPARE statement_name FROM sql_text /*定义*/
EXECUTE statement_name [USING variable [,variable...]] /*执行预处理语句*/
DEALLOCATE PREPARE statement_name /*删除定义*/


复制代码 代码如下:

mysql> PREPARE prod FROM "INSERT INTO examlple VALUES(?,?)";
mysql> SET @p='1';
mysql> SET @q='2';
mysql> EXECUTE prod USING @p,@q;
mysql> SET @name='3';
mysql> EXECUTE prod USING @p,@name;
mysql> DEALLOCATE PREPARE prod;


例如:
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)
--------------------------------------------------------------------------------------
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表