Home Database Mysql Tutorial MySQL prepare语句的SQL语法_MySQL

MySQL prepare语句的SQL语法_MySQL

May 27, 2016 pm 02:29 PM

bitsCN.com

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)
Copy after login

从MySQL 5.0 开始,支持了一个全新的SQL句法:

PREPARE stmt_name FROM preparable_stmt;
EXECUTE stmt_name [USING @var_name [, @var_name] ...];
{DEALLOCATE | DROP} PREPARE stmt_name;
Copy after login

通过它,我们就可以实现类似 MS SQL 的 sp_executesql 执行动态SQL语句!

同时也可以防止注入式攻击!

为了有一个感性的认识,

下面先给几个小例子:

mysql> PREPARE stmt1 FROM 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
mysql> SET @a = 3;
mysql> SET @b = 4;
mysql> EXECUTE stmt1 USING @a, @b;
+------------+
| hypotenuse |
+------------+
 
| 5 |
+------------+
mysql> DEALLOCATE PREPARE stmt1;
mysql> SET @s = 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
 mysql> PREPARE stmt2 FROM @s;
mysql> SET @a = 6;
mysql> SET @b = 8;
mysql> EXECUTE stmt2 USING @a, @b;
+------------+
| hypotenuse |
+------------+
| 10 |
+------------+
mysql> DEALLOCATE PREPARE stmt2;
Copy after login

如果你的MySQL 版本是 5.0.7 或者更高的,你还可以在 LIMIT 子句中使用它,示例如下:mysql> SET @a=1;mysql>

PREPARE STMT FROM "SELECT * FROM tbl LIMIT ?"; mysql> EXECUTE STMT USING @a;
mysql> SET @skip=1; SET @numrows=5; phperz.com
mysql> PREPARE STMT FROM "SELECT * FROM tbl LIMIT ?, ?";
Copy after login


mysql> EXECUTE STMT USING @skip, @numrows; 使用 PREPARE 的几个注意点:

A:PREPARE stmt_name FROM preparable_stmt;


预定义一个语句,并将它赋给 stmt_name ,stmt_name 是不区分大小写的。

B: 即使 preparable_stmt 语句中的 ? 所代表的是一个字符串,你也不需要将 ? 用引号包含起来。

C: 如果新的 PREPARE 语句使用了一个已存在的 stmt_name ,那么原有的将被立即释放! 即使这个新的 PREPARE 语句因为错误而不能被正确执行。

D: PREPARE stmt_name 的作用域是当前客户端连接会话可见。

E: 要释放一个预定义语句的资源,可以使用 DEALLOCATE PREPARE 句法。

F: EXECUTE stmt_name 句法中,如果 stmt_name 不存在,将会引发一个错误。

G: 如果在终止客户端连接会话时,没有显式地调用 DEALLOCATE PREPARE 句法释放资源,服务器端会自己动释放它。

H: 在预定义语句中,CREATE TABLE, DELETE, DO, INSERT, REPLACE, SELECT, SET, UPDATE, 和大部分的 SHOW 句法被支持。

G: PREPARE 语句不可以用于存储过程,自定义函数!但从 MySQL 5.0.13 开始,它可以被用于存储过程,仍不支持在函数中使用! 下面给个示例:

 CREATE PROCEDURE `p1`(IN id INT UNSIGNED,IN name VARCHAR(11))BEGIN lable_exit: BEGIN SET 
 @SqlCmd = 'SELECT * FROM tA '; IF id IS NOT NULL THEN SET @SqlCmd = CONCAT(@SqlCmd , 'WHERE id=?'); 
 PREPARE stmt FROM @SqlCmd; SET @a = id; EXECUTE stmt USING @a; LEAVE lable_exit; END IF; 
 IF name IS NOT NULL THEN SET @SqlCmd = CONCAT(@SqlCmd , 'WHERE name LIKE ?'); 
 PREPARE stmt FROM @SqlCmd; SET @a = CONCAT(name, '%'); EXECUTE stmt USING @a; LEAVE lable_exit; END IF; 
 END lable_exit;END; CALL `p1`(1,NULL);CALL `p1`(NULL,'QQ');DROP PROCEDURE `p1`;
Copy after login

声明 此为转载

 以上就是MySQL prepare语句的SQL语法_MySQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to create a new connection to mysql in navicat How to create a new connection to mysql in navicat Apr 09, 2025 am 07:21 AM

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

See all articles