mysql functions, transactions, views, triggers

1. Function

CREATE FUNCTION f_name(paramters) returns dataType; return value; 

paramters can only be in. Input parameter parameter name type
must have return value.
Begin and end
returns cannot be added. The return value type is not added here.
Return is the value to be returned.
Example: Add two numbers

create function addfuntion(a int,b int) 
returns int return a + b; 
#执行函数 
select addfuntion(1,1); 

Note: The
function can only return one value. The
function generally does not involve data addition, deletion, modification, and check. It is a general function.
Calling a custom function is consistent with the calling system. No call is required. Use select to get the return value
. You cannot use SQL statements
in the function. The same
as sql statement that cannot be recognized in java, such as count(), sum(), avg(), max(), min()

2. Affairs

​ A transaction is a group of indivisible units that either succeed or fail at the same time
​ The integrity of the data before and after the transaction should be consistent. When
multiple users access data concurrently, one user’s transaction cannot be interfered by other users’ transactions. The data between multiple concurrent transactions must be isolated from each other.Once
a thing is committed, its changes to the data are permanent, and even if the database fails, it should not have any impact on it.

In MySQL, only databases or tables that use the Innodb database engine support transactions.
Use BEGIN, ROLLBACK, COMMIT to realize
BEGIN start a transaction
ROLLBACK transaction rollback
COMMIT transaction confirmation

Example in python:

import pymysql

try:
conn = pymysql.connect(host="ip",user="user",password="password",db="test1")
print("连接服务器成功!")

cursor = conn.cursor()
sql = "update student set name = \"jack2\" where s_id = 2 ;"
sql2 = "update student set name = rose21 where s_id = 3;" # money打错了将导致执行失败
try:
cursor.execute(sql)
cursor.execute(sql2)
conn.commit()
print("执行成功 提交")
except:
print("发送错误 回滚..")
conn.rollback()

except Exception as e:
print("连接服务器失败.....")
print(type(e),e)
finally:
if cursor:cursor.close()
if conn:conn.close()

Three View

Views can be used to control data permissions, or to simplify connection queries. Additions, deletions and changes to the view will be synchronized to the original table, but because the view is generally part of the field, it will generally fail. The
view is a virtual table, so the usage is the same as ordinary Table does not make any difference

Create views to control data field permissions or simplify query statements for multiple tables

CREATE VIEW car_location (车架号,layer,地区) as 
SELECT 
vehicle_purchase_invoice.frame_num,vehicle_purchase_invoice.layer,sys_location.name
from vehicle_purchase_invoice,sys_location
WHERE vehicle_purchase_invoice.layer = sys_location.layer;
#查看视图 
SELECT * from car_location WHERE 车架号 ='20B0062R9Y2548197';
#删除视图
DROP VIEW car_location;

Fourth, the trigger

1. Prepare the data

CREATE TABLE cmd (
id INT PRIMARY KEY auto_increment,
USER CHAR (32),
priv CHAR (10),
cmd CHAR (64),
sub_time datetime, #提交时间
success enum ('yes', 'no') #0代表执行失败
);

2. Error log table

CREATE TABLE errlog (
id INT PRIMARY KEY auto_increment,
err_cmd CHAR (64),
err_time datetime
);

3. Create a trigger

delimiter //
create trigger trigger1 after insert on cmd for each row
FOR EACH ROW表示任何一条记录上的操作满足触发事件都会触发该触发器,也就是说触发器的触发频率是针对每一行数据触发一次。
begin
if new.success = "no" then
insert into errlog values(null,new.cmd,new.sub_time);
end if;
end//
delimiter ;

DROP trigger trigger1;

4. Insert a record into the table cmd, trigger the trigger, and decide whether to insert the error log according to the conditions of the IF

INSERT INTO cmd (
USER,
priv,
cmd,
sub_time,
success
)
VALUES
('egon','0755','ls -l /etc',NOW(),'yes'),
('egon','0755','cat /etc/passwd',NOW(),'no'),
('egon','0755','useradd xxx',NOW(),'no'),
('egon','0755','ps aux',NOW(),'yes');

5. Check whether the records in the error log table are automatically inserted

select *from errlog;

Guess you like

Origin blog.csdn.net/Krystal_RonghuiLi/article/details/108000089