MySQL之预处理语句

MySQL 刘宇帅 4年前 阅读量: 905

什么是预处理语句(prepared statement)

有时候我们需要经常执行一类SQL,但是只是部分参数不一样,如果我们每次都直接执行带参数的 SQL 那么数据库每次都需要进行语法解析、优化、指定执行计划。预处理语句就是为了解决这总问题,预处理语句把这类 SQL 中的参数使用占位符替代,可以先把带占位符的语句发给数据库服务器,服务器会对其进行编译并保存起来,然后每次查询同一个 SQL 的时候只需要传入不同的参数即可,这样就可以达到一次编译多次运行。
预处理语句不仅能够提高 SQL 执行的性能也可以防止SQL注入,使用预处理语句我们就不需要在代码层对参数做过滤或转义。

预处理语句使用

使用 id 查询学生信息

mysql> prepare select_student from 'select * from students where id=?';
Query OK, 0 rows affected (0.01 sec)
Statement prepared

mysql> set @id=1;
Query OK, 0 rows affected (0.01 sec)

mysql> execute select_student using @id;
+----+------+--------+-----+------+---------------------+---------------------+
| id | no   | name   | sex | age  | created_at          | updated_at          |
+----+------+--------+-----+------+---------------------+---------------------+
|  1 | 0001 | 洛基   |   2 |   25 | 2019-12-20 20:00:00 | 2019-12-20 02:18:52 |
+----+------+--------+-----+------+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> set @id=2;
Query OK, 0 rows affected (0.00 sec)

mysql> execute select_student using @id;
+----+------+--------+-----+------+---------------------+---------------------+
| id | no   | name   | sex | age  | created_at          | updated_at          |
+----+------+--------+-----+------+---------------------+---------------------+
|  2 | 0002 | 冷锋   |   2 |   25 | 2019-12-20 20:00:00 | 2019-12-20 20:00:00 |
+----+------+--------+-----+------+---------------------+---------------------+
1 row in set (0.00 sec)

提示

功能待开通!


暂无评论~