当前位置:网站首页>How does MySQL prepare SQL (solve the problem that in query SQL preprocessing can only query one record)
How does MySQL prepare SQL (solve the problem that in query SQL preprocessing can only query one record)
2022-07-23 21:44:00 【Bald loves fitness】
One 、 Preface / summary
My colleague asked me a question this week ,SQL How to use placeholders in ? Preprocessing , Why did he use prepare It didn't work ;
1、prepare brief introduction
Execute one more time SQL When the sentence is , If you deal with this every time SQL sentence , Generate execution plan , It is bound to waste a certain amount of time .
SQL Preprocessing (Prepare), It's a special kind SQL Processing mode ; Preprocessing will not be performed directly SQL sentence , But first SQL Statement compilation , Generate execution plan , And then through Execute Order to carry SQL Parameter execution SQL sentence .
- Prepare Is widely used , most ORM There are frames API Support ;
- Prepare Can improve SQL Executive performance , It can also prevent SQL Security problems caused by injection ;
- Prepare Although the syntax varies greatly in each database , But usually we don't write by hand SQL, But use ORM Frame to do ;
2、prepare The origin of ?
from mysql Server execution sql In terms of the process ,SQL The execution process includes the following stages Lexical analysis -> Syntax analysis -> Semantic analysis -> Execute plan optimization -> perform .
Lexical analysis -> The two stages of parsing are called hard parsing .
- Lexical analysis and recognition sql Every word in ;
- Parsing SQL Whether the statement conforms to sql grammar , And get a grammar tree (Lex).
For, only the parameters are different , Others are the same sql, Their execution time is different, but the hard parsing time is the same .
And the same SQL As the query data changes , The execution time of multiple queries may be different , But the time of hard parsing is constant . So for sql Short execution time ,sql The higher the ratio of hard parsing time to total execution time .
Prepare The emergence of is to optimize the problem of hard parsing .
although Prepare stay execute Phase can save hard parsing time . But if sql Only once , And in prepare By , that sql The execution needs to interact with the server twice (Prepare and execute), And ordinary ( Not prepare) The way , Only one interaction is needed . Use this way prepare It will bring additional network overhead , Do more harm than good .
If the same sql It needs to be done many times , such as : With prepare How to execute 10 Time , Then only one hard parsing is needed . Now The extra network overhead is minimal ; therefore prepare It is more suitable for frequently executed SQL in .
Two 、prepare do IN Inquire about
MySQL Pretreatment is a group SQL Set of operations , It has no fixed syntax format , But in most cases, it will follow the following 3 Use... In two steps :
- Use PREPARE Instructions are predefined SQL Statement template ;
- Use SET Instruction definition SQL Parameters ;
- Use EXECUTE Instructions carry parameters to execute SQL Templates .
1、 Preprocessing IN The query failed !
SQL:
prepare myFun from 'select * from user where id IN (?)';
set @str='1,2';
execute myFun using @str;
Above SQL Can do three things :
- Create preprocessing SQL(
myFun), Where you want to use variables use ? Express ; - Set a variable
@str; - Perform preprocessing SQL(
myFun),USINGFollowed by parameters , If there are multiple parameters ( That is, multiple placeholders?) Use English commas,Separate ;
SQL Execution results :
from SQL As a result of implementation , Find preprocessing SQL Not fully effective , Only one row of records was found ; Normally, two lines of records should be found ;
2、 Solve pretreatment IN Query failure
Use as follows SQL Replace :
prepare myFun from 'select * from user where FIND_IN_SET(id,?)';
set @str='1,2';
execute myFun using @str;
SQL Execution results ( In line with expectations ):
3、MyBatis and JDBC Dynamic in IN Inquire about
mybatis Support in The dynamics of the sql Inquire about , Its input parameter can be a Collection, The bottom layer will Collection The content of is constructed using English commas , Delimited string ; It can also be an English comma , Delimited string .
And the original jdbc in sql I won't support it IN Directly for a single placeholder ? Pass in a comma concatenated string , for example in (‘001’, ‘002’), Developers need to build placeholders according to the number of parameters passed in ? The number of ;
For example, pass in an array or List,{‘001’, ‘002’}; Need to construct in by :in(?, ?);
And then through PreparedStatement#setString() Methods build dynamically SQL sentence ,.
边栏推荐
- Redis常用命令对应到Redisson对象操作
- 寻找消失的类名
- Basic syntax of MySQL DDL and DML and DQL
- U++ 学习笔记 控制物体Scale
- How to implement desktop lyrics in pyqt
- 【arxiv】第一次上传论文小记
- 博客总排名为918
- pulsar开源消息队列_了解Pulsar---Pulsar工作笔记001
- Postgraduate entrance examination | advanced mathematics Chapter4 indefinite integral
- Practice data Lake iceberg lesson 37 kakfa write the enfour, not enfour test of iceberg's icberg table
猜你喜欢

2022-7-23 12点 程序爱生活 小时线顶背离出现,保持下跌趋势,等待反弹信号出现。

欧氏聚类(API)及其单木分割

Openlayers instances advanced mapbox vector tiles advanced mapbox vector maps

Why cluster chat server introduces load balancer

Customer exit variable in query

Yushu A1 robot dog gesture control

Basic principle of synchronized lock

寻找消失的类名

Be a professional software craftsman

NLP field history most complete must read classic papers classification, sorting and sharing (with Chinese analysis)
随机推荐
Why cluster chat server introduces load balancer
PCL error: error c2589 "(": "::" illegal mark on the right)
(note) learning rate setting of optimizer Adam
Given an array composed of numbers, realize the name whose output ID is a number and sorted from small to large
阿里onedate分层思想
MySQL如何对SQL做prepare预处理(解决IN查询SQL预处理仅能查询出一条记录的问题)
Hezhou esp32c3 hardware configuration information serial port printout
宇树A1机器狗手势控制
Use Gaode map JS API 2.0 to load the starting and ending path tracks
How to implement desktop lyrics in pyqt
Still have 1 requests outstanding when connection from slaveX/X.X.X.X:33202 is closed
合宙ESP32C3硬件配置信息串口打印輸出
Several methods of obtaining longitude and latitude by cesium
启牛是什么?请问一下手机开户股票开户安全吗?
Jianzhi offer II 115. reconstruction sequence: topological sorting construction problem
Flink principle and development summary (detailed)
DBSCAN点云聚类
Principle and implementation of hash table, unordered set and mapping
数据库压力测试方法小结
Complete set of official openlayers instances