当前位置:网站首页>MySQL stored procedure

MySQL stored procedure

2022-06-13 05:56:00 A programmer in a wig

Preface

MySQL 5.0 The version starts to support stored procedures .

stored procedure (Stored Procedure) It's a complex program stored in a database , A database object that can be called by an external program .

Stored procedures are designed to accomplish specific functions SQL Statements set , Compiled, created and stored in a database , The user can specify the name of the stored procedure and give the parameters ( When needed ) To call execution .

Stored procedures are very simple in mind , Database SQL Language level code encapsulation and reuse .

advantage

  • Stored procedures can be encapsulated , And hide complex business logic .
  • Stored procedures can return values , And can accept parameters .
  • Stored procedures cannot be used SELECT Command to run , Because it's a subroutine , And view table , Data tables or user-defined functions are different .
  • Stored procedures can be used for data validation , Enforce business logic, etc .

shortcoming

  • stored procedure , Often customized to a specific database , Because the supported programming languages are different . When switching to the database system of other manufacturers , You need to rewrite the original stored procedure .
  • Performance tuning and writing of stored procedures , Limited by various database systems .

First example

We use a simple example to learn the basic syntax of stored procedures
Basic grammar :

CREATE PROCEDURE produce_name( parameter list )
begin --  Indicates the beginning of the process body { --
   --  Here is your business logic code  --
end --  Indicates the end of the process body } -- 

Case study :
Let me start with a few questions , What I use here is Navicat.Navicat The default statement end symbol in is “;” But in a stored procedure, we may have multiple statements , Every statement ends with “;”, To prevent the creation of stored procedures Navicat Just use “;” As a closing sign , We need to restate the closing symbol :

DELIMITER $$
 or 
DELIMITER //

tips : Of course, you can define this symbol yourself ( Don't be too casual ).
Come on ! Look at the case :

--  Create a stored procedure to count the number of books  --
--  Modify end tag  --
DELIMITER $$
DROP PROCEDURE IF EXISTS proc_bookcount;
--  Create stored procedure  --
CREATE PROCEDURE proc_bookcount()
BEGIN
	--  Declare variables  --
	DECLARE v_count int;
	--  Assign a value to a variable  --
	select count(*) into v_count from g_book;
	--  Inquire about count --
	select v_count;
END $$
--  Change the end tag back  --
DELIMITER ;

After execution, view the structure viewport on the left :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-jRIr1EJG-1632642140911)(MySQL- stored procedure .assets/image-20210926085606454.png)]

Execute stored procedures :

--  Execute stored procedures  --
CALL proc_bookcount;

Delete stored procedure :

DROP PROCEDURE proc_bookcount;

Of course, the stored procedure above just executes a query statement .
There can be business logic in stored procedures , Then basic process control is required .
So we have to write a certain quality of stored procedures , You need to understand some basic syntax of stored procedures .
tips: As long as you have learned programming , It's all very simple .
Of course , What makes us sick is , The syntax of stored procedures in each different database is different . This is also the biggest drawback of stored procedures mentioned earlier .

Basic grammar

Variable

MySQL The variables of are : Global variables , Session variables , User variables , System variables , local variable .
Here we focus on the use of stored procedures , For the time being, only local variables .
Local variables are declared in BEGIN and END Between variables , The scope is in BEGIN and END Between .
Declare variables : Use DECLARE keyword

DECLARE var_name var_type [default_value]

Case study :

--  Modify end tag  --
DELIMITER $$
--  Create stored procedure  --
CREATE PROCEDURE proc_bookcount()
BEGIN
	--  Declare variables  --
	DECLARE v_isbn varchar(255) default '9787111573319';
	DECLARE v_title varchar(255);
	--  Use set Assign a value to a variable  --
	set v_isbn = '9787302444541';
	--  Use  select into  To assign values to variables  --
	SELECT title into v_title from g_book where isbn = v_isbn;
	--  Show two variables  --
	select v_isbn,v_title;
END $$
--  Change the end tag back  --
DELIMITER ;

variable declaration :

DECLARE v_isbn varchar;

There are two ways to assign values to variables :
The way 1: direct set

set v_bookid = 1;

The way 2: Use select into

select count(*) into v_count from book

tips:select The following columns must correspond to variables .

such as :

select isbn,title into v_isbn,v_title from book where booid = 1

Case study :

  • Local variables must be placed at the beginning of the stored procedure
CREATE PROCEDURE proc_bookcount()
BEGIN
	--  Declare variables  --
	DECLARE v_isbn varchar(255) default '9787111573319';
	DECLARE v_title varchar(255);
	--  Use set Assign a value to a variable  --
	set v_isbn = '9787302444541';
	--  Use  select into  To assign values to variables  --
	SELECT isbn,title into v_isbn,v_title from g_book where isbn = v_isbn;
	--  Show two variables  --
	select v_isbn,v_title;
END $$

Flow control statement

Branch statement

[1] if…then …else
grammar

--  Only if Structure  --
if  Conditions   then
  Executed statement 
end if;
--if.. else --
if  Conditions   then
 	if sentence 
else
	else sentence 
end if;
--  Multiple branches  --
if  Conditions   then
 	if sentence 
elseif  Conditions   then
	 sentence ...
	.....
else
	else sentence 
end if;

Case study :

--  Branch statement IF --
DELIMITER $$
create PROCEDURE proc_demo()
begin
	declare v_num int;
	declare v_result varchar(100) default ' Odd number ';
	set v_num = CEIL(RAND() * 100);
	IF mod(v_num , 2) = 0 THEN
		set v_result = ' even numbers ';
	end if;
	select CONCAT(' Numbers ',v_num,' yes ',v_result);
end $$
DELIMITER ;
-- if .. else --
DELIMITER $$
create PROCEDURE proc_demo()
begin
	declare v_num int;
	declare v_result varchar(100);
	set v_num = CEIL(RAND() * 100);
	IF mod(v_num , 2) = 0 THEN
		set v_result = ' even numbers ';
	ELSE
		set v_result = ' Odd number ';
	end if;
	select CONCAT(' Numbers ',v_num,' yes ',v_result);
end $$
DELIMITER ;
--  multiple if --
DELIMITER $$
create PROCEDURE proc_demo()
begin
	declare v_num int;
	declare v_result varchar(100);
	set v_num = CEIL(RAND() * 100);
	IF mod(v_num , 2) = 0 THEN
		set v_result = ' even numbers ';
	elseif mod(v_num , 3) THEN
		set v_result = '3 Multiple ';
	ELSE
		set v_result = ' Odd number ';
	end if;
	select CONCAT(' Numbers ',v_num,' yes ',v_result);
end $$
DELIMITER ;

Call the above procedure

CALL proc_demo;

[2]CASE structure
Serve directly :

DELIMITER $$
CREATE PROCEDURE PROC_DEMO()
BEGIN
	DECLARE v_num int;
	set v_num = ROUND(RAND() * 10);
	CASE v_num
	when MOD(v_num,2)=0 THEN
		select ' even numbers ';
	when MOD(v_num,3)=0 THEN
		select '3 Multiple ';
	else
		select ' Odd number ';
	end case;
END $$
DELIMITER ;

Loop statement

[1]while ···· end while

while  Conditions  do
    -- The loop body 
end while
DELIMITER $$
CREATE PROCEDURE PROC_DEMO()
BEGIN
	DECLARE v_num int default 0;
	while v_num < 10 do
	insert into temp values(v_num);
	set v_num = v_num + 1;
	end while;
END $$
DELIMITER ;

[2]repeat···· end repeat

repeat
    -- The loop body 
until  The loop condition   
end repeat;
DELIMITER $$
create PROCEDURE proc_demo()
begin
	declare v_num int default 0;
	repeat 
		insert into temp values(v_num);
		set v_num = v_num + 1;
		--  Exit loop  --
		until v_num >=10 end repeat;
end $$
DELIMITER ;

[3]loop ·····endloop

loop The loop does not require initial conditions , This and while Cyclic similarity , At the same time with repeat There is no end condition for a loop , leave The meaning of a sentence is to leave a loop .

DELIMITER $$
create PROCEDURE proc_demo()
begin
	declare v_num int default 10;
	--  Here is a loop marker loop_lable, The name is optional  --
	loop_lable:loop 
		insert into temp values(v_num);
		set v_num = v_num + 1;
		--  Exit loop  --
		if v_num >= 20 THEN
			leave loop_lable;
		end if;
	end loop;
end $$
DELIMITER ;

Use loop Implement a double-layer loop :

DELIMITER $$
create PROCEDURE proc_demo()
begin
	declare v_num int default 0;
	declare v_inner_number int default 0;
	--  Here is a loop marker loop_lable, The name is optional  --
	loop_lable:loop 
		set v_inner_number = 0;
		loop_inner_lable:loop
			insert into temp values(CONCAT(v_num,v_inner_number));
			set v_inner_number = v_inner_number + 1;
			if v_inner_number >= 5 THEN
				leave loop_inner_lable;
			end if;
		end loop;
		set v_num = v_num + 1;
		if v_num >= 3 THEN
			leave loop_lable;
		end if;
	end loop;
end $$
DELIMITER ;

Parameters of stored procedure

MySQL Parameters of stored procedure are used in the definition of stored procedure , There are three types of parameters ,IN,OUT,INOUT, In the form of :

CREAT EPROCEDURE  Stored procedure name ([[IN |OUT |INOUT ]  Parameter name   Data classes ...])
  • IN Input parameters : Indicates that the caller passes a value... To the procedure ( The incoming value can be literal or variable )
  • OUT Output parameters : Indicates that the procedure passes out a value to the caller ( Multiple values can be returned )( Outgoing values can only be variables )
  • INOUT Input/output parameter : It means that the caller passes in a value to the procedure , It also indicates that the procedure passes out a value to the caller ( Values can only be variables )

1、in Input parameters

It can be simply understood as java Method parameters
To ensure that our data table structure does not leak out , So we prepare a storage add data

--  Create a stored procedure to add books  -- 
DELIMITER $$
create procedure proc_addbook(in p_isbn varchar(255),in p_title varchar(255),in p_cost float,p_price float,p_pid varchar(10),p_category int)
BEGIN
	insert into g_book values(p_isbn,p_title,p_cost,p_price,p_pid,p_category);
END $$
DELIMITER ;

forehead ~~~~
To call a stored procedure with input parameters, you need to pass in the corresponding parameters

call proc_addbook('95286589',' A history of scrap iron training ',56.3,185,'P005',1)

2、out Output parameters

Simply understood as java The return value of the method in

--  Stored procedure that outputs parameters  --
--  Define stored procedures , Query the number of books of the publishing house with the specified name , And return with output parameters  --
DELIMITER $$
create PROCEDURE proc_countbypublisher(in p_pname varchar(255),out p_count int)
BEGIN
	--  Assign the result of the query to the output parameter  --
	select count(*) into p_count from g_book where pid = (select pid from g_pubsher where pname = p_pname);
end $$
DELIMITER ;

Call a stored procedure with output parameters

set @count_out=0;
call proc_countbypublisher(' Mechanical industry press ',@count_out);
select @count_out ' The number of books published by the machinery industry press ';

Description of user variables :

 During the above call , We used the user variable  @count_out
 User variables are all in the form of @ start , The default is valid in one connection .

3、inout Input parameters

forehead !!! Literally . Can input , It can also output . In fact, it's good to know , Try not to use this type of parameter

-- inout Parameter stored procedure  --
--  Define stored procedures , Query the number of books of the publishing house with the specified name , And return with output parameters  --

DELIMITER $$
create PROCEDURE proc_countbypublisher1(inout param varchar(255))
BEGIN
	--  Assign the result of the query to the output parameter  --
	select count(*) into param from g_book where pid = (select pid from g_pubsher where pname = param);
end $$
DELIMITER ;

call

--  Called with inout Stored procedure  --
set @param = ' Mechanical industry press ';
call proc_countbypublisher1(@param);
select @param ' The number of books published by the machinery industry press '

JDBC Calling stored procedure

Prepare a stored procedure for paging queries

In this stored procedure, you need to execute the string form sql, User variables are required .

DELIMITER $$
create PROCEDURE proc_page(tableName varchar(255),pageNum int,pageSize int,term varchar(255),out total int)
BEGIN
	declare startIndex int default 0;
	declare done int default 0;
	--  Declare the total number of entries saved by the user variable  --
	set @v_total = 1;
	--  perform sql Total number of queries   The user variables here are compiled , Can continue to use  --
	set @v_total_sql = concat('select count(*) into @v_total from ',tableName);
	if term!=''  THEN
		set @v_total_sql = CONCAT(@v_total_sql,' where ',term);
	end if;
	prepare s0 from @v_total_sql;
	execute s0;
	deallocate prepare s0;
	set total = @v_total;
	--  Splice according to parameters sql sentence  --
	set @v_sql = CONCAT('select * from ',tableName);
	if term!=''  THEN
		set @v_sql = CONCAT(@v_sql,' where ',term);
	end if;
	--  Calculate the starting position  --
	set startIndex = (pageNum-1)*pageSize;
	set @v_sql = CONCAT(@v_sql,' limit ',startIndex,',',pageSize);
	prepare s1 from @v_sql;
	execute s1;
	deallocate prepare s1;
end $$
DELIMITER ;


drop PROCEDURE proc_page

--  Call tests --
set @out_total = 0;
call proc_page('g_book',1,3,'',@out_total);
select @out_total;

JDBC Calling stored procedure :

package com.st.dao;

import java.sql.*;
import java.util.concurrent.Callable;

/** * @author  Procedures for wearing wigs  */
public class ProcTestDAO extends BaseDAO{
    
    public void queryPaperByProc() throws SQLException {
    
        Connection con = getCon();
        // CallableStatement Can be used to execute stored procedures 
        // sql The statement must use {} The parcel .  Whatever the parameter is, use ? placeholder 
        CallableStatement cst = con.prepareCall("{call proc_page(?,?,?,?,?)}");
        // Set parameters 
        //  Input parameters are set directly 
        cst.setString(1,"paper");
        cst.setInt(2,2);
        cst.setInt(3,5);
        cst.setString(4,"paper_title like '% questionnaire %'");
        // The output parameter is to be registered .
        cst.registerOutParameter(5, Types.INTEGER);
        // perform 
        ResultSet rs = cst.executeQuery();
        //  Get the value of the registered parameter 
        int total = cst.getInt(5);
        System.out.println(" Total number :"+total);
        while(rs.next()){
    
            System.out.println(rs.getString("paper_title"));
        };
    }

    public static void main(String[] args) {
    
        try {
    
            new ProcTestDAO().queryPaperByProc();
        } catch (SQLException e) {
    
            e.printStackTrace();
        }
    }
}

原网站

版权声明
本文为[A programmer in a wig]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280506133261.html