MySQL learning four transactions, variables, triggers, functions, stored procedures

Requirement: There is a bank account table, user A transfers money to user B; account A decreases first, and account B increases, but after A finishes the operation, the power is cut off.

Solution: A reduces the money, but does not modify the data sheet immediately; after B receives the money, modify the data sheet at the same time


transaction security

Transaction: transaction, a series of consecutive operations to occur
Transaction Safety: A mechanism to protect successive operations while satisfying (implementing)

The meaning of transaction security: ensuring the integrity of data operations


--Create an account table
create table my_account(
number char(16) not null unique comment 'account',
name varchar(20) not null,
money decimal(10) default 0.0 comment 'account balance'
)charset utf8;

insert into my_account values('0000000000000001','Zhang San',1000),('00000000000000002','Li Si',1000);

alter table my_account add id int primary key auto_increment first;

update my_account set money = money - 1000 where id= 1;


transaction operation
There are two types of transaction operations: automatic transactions (default) and manual transactions

Manual Transactions: Operational Processes
1. Open transaction: tell the system that all the following operations (writes) should not be written directly to the data table, but should be stored in the transaction log first
-- start transaction
start transaction;

2. Perform transaction operations: a series of operations
	a) Li Si's account decreased
update my_account set money = money - 1000 where id = 2;
	b) Zhang San's account increased
update my_account set money = money + 1000 where id = 1;

3. Close the transaction: selectively save the results of the operations in the log file to the data table (synchronization) or
Clear the transaction log directly (all the original operations are cleared)
	a) Commit transaction: synchronize data table (operation succeeded) commit;
	b) Roll back the transaction; clear it directly (the operation fails) rollback;
-- commit transaction
commit;


business principle
After the transaction is opened, the subsequent operations (write) will be written to the temporary log file first.
Receive the SQL statement and execute the SQL statement; the result is first written to the temporary log file;
Query operation: It will be queried from the data table, and returned after processing the results of the temporary log file
End of transaction: commit or rollback, clear the temporary log file, commit will be synchronized to the data table,
rollback is to clear directly
If you disconnect, the temporary transaction file is automatically emptied.


Rollback point
After a successful operation is completed, subsequent operations may succeed or fail, but regardless of
Success or failure, the previous operations have been successful; you can set a point at the current successful position;
Instead of returning all operations, subsequent failed operations can return to this position, and this point is called the rollback point.

Set rollback point syntax: savepoint rollback point name

Back to the rollback point syntax: rollback to rollback point name

--Rollback point operation

-- start transaction
start transaction;
--Transaction 1: Zhang San adds money
update my_account set money=money+10000 where id = 1;
--View Results
select * from my_account;
-- set rollback point
savepoint sp1;
--Bank tax deduction
update my_account set money=money-10000*0.05 where id=2; --错误
--View Results
select * from my_account;
-- rollback to rollback point
rollback to sp1;
--View Results
select * from my_account;
-- continue
update my_account set money=money-10000*0.05 where id=1;
--View Results
select * from my_account;
-- commit transaction
commit;


Transaction Features: Four Features
	A: Atomicity, the entire operation of the transaction is a whole, indivisible, either all succeed or all fail
	C: Consistency, before and after the transaction operation, the data in the data table does not change
	I: Isolation, transaction operations are not affected by phase-to-isolation
	D: Persistence, once the data is submitted, it cannot be changed, permanently changing the data in the data table
	
Lock mechanism: innodb is row lock by default, but if the index is not used during the transaction operation,
Then the system will automatically retrieve data from the full table and automatically upgrade to a table lock.
	Row lock: only the current row is locked, other users cannot operate
	Table lock: The entire table is locked, and other users cannot operate it.



variable
Variables are divided into system variables and custom variables

System variables: system-defined variables, system variables are used to control the performance of the server, such as
autocommit,auto_increment_increment等

View system variables
show variables ; -- view all system variables
	
View specific variable values: any content returned with data is viewed by select
select @@variable name;

-- view variable value
select @@version,@@autocommit,@@auto_increment_offset;

Modify system variables
Divided into two ways: session level and global level and global level

Session level: Temporary modification

--Modify the session level variable, the current client connection is valid
set variable name = value; set @@variable name = value;
set autocommit = 0 ;

Global level: one modification, permanent effect (effective for all clients)
set global variable name = value;


custom variable
In order to distinguish system variables, the system stipulates that user-defined variables must use an @ symbol
set @variable name = value;

set @name = 'Zhang San';

select @name;

An assignment symbol defined by mysql:=

set @age := 19;

select @age;


mysql allows to get data from the data table, and then assign it to the variable: two ways

1. While assigning value, check the result (only use :=, the = sign will be parsed as a comparison)
select @variable name:= field name from data source; -- get the value from the field and assign it to the variable name

-- Get the data from the table and assign it to the variable
select @name := name from my_student;

2. Only the assignment does not look at the result, the requirements are very strict: the data record can only have one record
select field table from data source into @variable name
select name,age from my_student where id=2 into @name,@age;

All custom variables are session level: the current client is valid for the current connection
All custom variables are database agnostic (user level)


Demand: There are two, one order table and one product table, each generating an order means that the inventory of the product needs to be
reduce

trigger
Bind a piece of code to a table in advance, and when some content in the table changes (add, delete, modify) the system
Code execution is automatically triggered.

Event type, trigger time, trigger object
	Event type: addition, deletion and modification, three types of insert delete update
	Trigger time: before and after, two before and after
	Trigger object: each record (row) in the table

A table can only have one type of trigger with one firing time; a table can have up to 6 triggers


Create a trigger
In the mysql advanced structure: there are no curly brackets, they are replaced by the corresponding character symbols

basic grammar
-- Temporarily modify the statement terminator
delimiter custom symbol: the subsequent code will only end when the custom symbol is encountered

create trigger trigger name trigger time event type on table name for each row
begin -- represents an opening brace; begin
	...which is the content of the trigger: each line of content must use a statement terminator, a semicolon
end -- represents the right parenthesis: end
-- statement end symbol
custom symbol

--Fix the temporary changes
delimiter


--create table
create table my_goods(
	id int primary key auto_increment,
	name varchar(20) not null,
	price decimal(10,2) default 1,
	inv int comment 'stock'
)charset utf8;

insert into my_goods values(null,'iphone6s',5288,100),(null,'s6',5300,100);

create table my_order(
	id int primary key auto_increment,
	g_id int not null comment '商品ID',
	g_number int comment 'item quantity'
)charset utf8;


-- Trigger: an order is generated, and the inventory of the item is reduced
-- Temporarily modify the statement terminator
delimiter $$

create trigger after_order after insert on my_order for each row
begin
	update my_goods set inv = inv - 1 where id = 2;
end
$$
delimiter  ;


View triggers

View all triggers or fuzzy matches
show triggers\G;

-- View trigger creation statement
show create trigger trigger name;

show create trigger after_order\G


All triggers are stored in a system table information_schema.triggers

select * from information_schema.triggers


Use triggers
No need to call manually, but when something happens, it will be triggered automatically

--Order insertion record will be triggered automatically
--The trigger works, after the order is generated, the number of corresponding items is reduced
--The reduction of the current commodity is not the commodity generated in the order; it is the fixed commodity (unreasonable)
--insert order
insert into my_order values(null,1,2);

Modify Triggers & Delete Triggers

Triggers cannot be modified, they can only be deleted first and then added

drop trigger trigger name;
--delete trigger
drop trigger after_order;


trigger record
Regardless of whether the trigger is fired or not, as long as an operation is currently ready to be performed, the system will convert the current state of the record to be operated on
and the new state after the execution is respectively reserved for trigger use: among them, the current state to be operated is saved in old,
The possible forms after the operation are saved to new

old represents the old record, new represents the new record
	There is no new when deleting, and no old when inserting
old and new represent the record itself, any record has field names in addition to data
Use the old. field name / new. field name (new represents the result after the assumption occurs)


delimiter $$
create trigger after_order after insert on my_order for each row
begin
	update my_goods set inv = inv - new.g_number where id = new.g_id;
end
$$
delimiter  ;

insert into my_order values(null,1,2);


code execution structure

Three kinds: sequential structure, branch structure, loop structure

branch structure
Implement preparing multiple code blocks and selectively execute a certain piece of code according to conditions

only if branch in mysql

basic grammar
if conditional judgment then
	--The code to be executed when the condition is met
else
	--The code to be executed if the condition is not met
end if;

The trigger is combined with the If branch to determine whether the product inventory is sufficient, and the product order cannot be generated if it is not enough.


--Insufficient inventory: The trigger does not provide an ability to prevent the event from happening, violently reporting an error
delimiter %%
create trigger before_order before insert on my_order for each row
begin
		select inv from my_goods where id = new.g_id into @inv;
		if @inv < new.g_number then
			insert into XXX values(XXX);
		end if;
end
%%
delimiter   ;

--insert order
insert into my_order values(null,1,1000);


loop structure
A certain piece of code is repeatedly executed under a specified condition
while loop

while conditional judgment do
	--The code to be executed when the condition is met
	--Change the loop condition
end while;

Loop control: loop judgment and control within the loop
There is no corresponding continue and break in mysql; but there are alternatives
iterate iteration, similar to continue, the code behind is not executed, the loop starts over
leave leaves, similar to break;

Use method iterate/leave loop name;

--define the loop name
Loop name: while condition do
	--loop body
	--loop control
		leave/iterate loop name
end while;


function
Encapsulate a block of code into a structure. When the code needs to be executed, call the structure to execute it (code reuse)

Divided into two categories: system functions and custom functions

System function: call it directly
Any function has a return value, so the call to the function is called through select.

The basic unit of strings in mysql, the most commonly used are characters
substring String interception, the character is the unit substring(str,pos,len);
char_length character length
length byte length
instr determines whether a string exists in a specific string
lpad left padding, fill the string with a specified length according to a specified padding method
insert string replacement
strcmp string comparison

--define two variables
set @cn = 'Hello world';
set @en = 'hello world';

--String interception, the subscript of the string in mysql starts from 1, and the interception unit is character
select substring(@cn,1,1);
select substring(@en,1,1);

-- character length
select char_length(@cn),char_length(@en),length(@cn),length(@en);

--string search, 0 means not found
select instr(@cn,'bound'),instr(@en,'ll'),instr(@cn,'know');

--string padding
select lpad(@cn,20,'welcome'),lpad(@en,20,'hello');

-- string replacement
select insert(@in,3,3,'y'),@in;



custom function
Function elements: function name, parameter list (formal and actual parameters), return value, function body

create grammar
create function function name ([formal parameter list]) returns data type--specify the data type to be returned
begin
	-- function body
	--Return value return type (specified data type)
end

-- create function
create function display1() returns int
return 100;

--Call functions
select display1();

-- view all functions
show function status [like ''];

The function belongs to the specified data and can only be called under the corresponding database

View function creation
show create function function name;

show create function display1;

Modify function & delete function
The function cannot be modified, delete it first and then add it
drop function function name;

drop function display1;

function parameter
There are two types of parameters: the parameters in the definition are called formal parameters,


--Function: Calculate the sum between 1-specified numbers
-- Summation: any variable to be modified must use the set keyword
--The variable defined by @ is a global variable, not a local variable
delimiter $$
create function display1(int_1 int) returns int
begin
	set @i = 1 ;
	set @res = 0 ;
	while @i <= int_1 do
		set @res =@res+ @i;
		set @i = @i+1;
	end while;
	return @res;
end
$$
delimiter  ;

Variables defined with @ inside a function can also be accessed outside the function

scope
Scope in mysql is the same as scope in JS
	Global variables can be used anywhere; local variables can only be used inside functions
Global variables: defined with the set keyword, marked with the @ symbol
Local variables: declared with the declare keyword, without the @ symbol; declaration of all local variables


--Sum: 1-the sum between the specified numbers, requiring multiples of 5 not to be added
delimiter $$
create function display2(int_1 int) returns int
begin
	declare i int default 1 ;
	declare res int default 0 ;
	mywhile:while i <= int_1 do
		if i%5=0 then
			set i = i+1;
			iterate mywhile;
		end if;
		set res = res +i;
		set i = i+1;
	end while;
	return res;
end
$$
delimiter  ;


stored procedure
A stored procedure is a function that does not return a value

create process

create procedure procedure name ([parameter list])
begin
	--process body
end

--creation process
--Assuming that data needs to be displayed during the process: use select
create procedure pro1()
	select * from my_student;
	
View the process

View all processes

show procedure status [like ''];

--View procedure creation statement
show create procedure pro1;

call procedure
The procedure has no return value, and select cannot be accessed
Procedures have a special call keyword call

call pro1();


Modify Process & Delete Process
The process cannot be modified, it can only be deleted first and then added
drop procedure procedure name;

drop procedure pro1;

Process parameters
The parameters of the function need to be specified by data type, and the procedure is stricter than that of the function

Overweight also has its own type restrictions: three types
	in: The data is only passed in from the outside for internal use (value transfer); it can be a value or a variable
	out: only allowed for internal use in the process (without external data), for external use (pass by reference, external data will be used by
		Empty first before entering into the interior), only the variable
	inout: External can be used internally, and internal modifications can also be used externally; typical pass by reference, only variables

Basic use:
create procedure procedure name (in parameter name data type, out parameter name data type, inout parameter name data type)


--process parameters
The value of --int_2 must be null, and the Out data will be cleared first
delimiter $$
create procedure pro1(in int_1 int,out int_2 int,inout int_3 int)
begin
	select int_1,int_2,int_3;
end
$$
delimiter  ;

Calls: parameters of type out and inout must be passed in variables instead of numbers
set @int_1=1;
set @int_2=2;
set @int_3=3;
select @int_1,@int_2,@int_3;
call pro1(@int_1,@int_2,@int_3);

-- Local variables are not related to global variables
delimiter $$
create procedure pro2(in int_1 int,out int_2 int,inout int_3 int)
begin
	select int_1,int_2,int_3;
	
	set int_1 = 10 ;
	set int_2 = 100;
	set int_3 = 1000;
	
	select int_1,int_2,int_3;
	select @int_1,@int_2,@int_3;
	
	set @int_1 = 'a';
	set @int_2 = 'b';
	set @int_3 = 'c';
	
	select int_1,int_2,int_3;
	select @int_1,@int_2,@int_3;
end
$$
delimiter  ;
select @int_1,@int_2,@int_3;
Finally: after the stored procedure call ends, the system will return the local variable to the global variable, only out, inout;



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327059812&siteId=291194637