ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

MySQL数据库之预处理

2020-12-15 13:33:23  阅读:237  来源: 互联网

标签:set chinese 数据库 +-------+------+---------+------+ sec MySQL sel 预处理


预处理

  • 概念

    • 每个代码的段的执行都要经历
      • 词法分析——语法分析——编译——执行
    • 预编译一次,可以多次执行
    • 用来解决一条SQL语句频繁执行的问题
  • 语法

    • 预处理语句:prepare 预处理名字 from ‘sql语句’
    • 执行预处理:execute 预处理名字 [using 变量]
    • MySQL中变量以@开头
    • 通过set给变量赋值
    • ?是位置占位符

不带参数的预处理

MariaDB [sel]> prepare stmt from 'select * from grades';
# `Query OK, 0 rows affected (0.007 sec)`
# `Statement prepared`

MariaDB [sel]> execute stmt;
+-------+------+---------+------+
| name  | sex  | chinese | math |
+-------+------+---------+------+
| Sunny | boy  |      93 |   96 |
| Jerry | boy  |      97 |   91 |
| Marry | girl |      95 |   94 |
| Tommy | boy  |      98 |   94 |
+-------+------+---------+------+
# `4 rows in set (0.000 sec)`

带一个参数的预处理

MariaDB [sel]> prepare stmt from 'select * from grades where name=?';
# `Query OK, 0 rows affected (0.000 sec)`
# `Statement prepared`

MariaDB [sel]> delimiter //
MariaDB [sel]> set @name='Sunny';
    -> execute stmt using @name //
# `Query OK, 0 rows affected (0.007 sec)`

+-------+------+---------+------+
| name  | sex  | chinese | math |
+-------+------+---------+------+
| Sunny | boy  |      93 |   96 |
+-------+------+---------+------+
# `1 row in set (0.008 sec)`

传递多个参数

MariaDB [sel]> prepare stmt from 'select * from grades where chinese<? and sex=?' //
# `Query OK, 0 rows affected (0.000 sec)`
# `Statement prepared`

MariaDB [sel]> set @chinese=97;
    -> set @sex='boy';
    -> execute stmt using @chinese,@sex //
# `Query OK, 0 rows affected (0.000 sec)`

# `Query OK, 0 rows affected (0.001 sec)`

+-------+------+---------+------+
| name  | sex  | chinese | math |
+-------+------+---------+------+
| Sunny | boy  |      93 |   96 |
+-------+------+---------+------+
# `1 row in set (0.007 sec)`

标签:set,chinese,数据库,+-------+------+---------+------+,sec,MySQL,sel,预处理
来源: https://www.cnblogs.com/SharkJiao/p/14138002.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有