MySQL flip-flop trigger instance detailed

Source: Internet
Author: User
Tags log log rollback

MySQL seems to be starting from 5.0.2 version to support the function of the trigger, this blog to introduce the trigger, first of all, or talk about the concept of something:

What is a trigger

A trigger is a database object that is related to a table, fires when a condition is met, and executes a collection of statements defined in the trigger. This feature of triggers helps the application ensure data integrity on the database side.

For example, you now have two tables "user table" and "Log Table", when a user is created, you need to insert the log log in the journal table, if you do not use triggers, you need to write programming language logic to implement, but if you define a trigger, The purpose of a trigger is to insert a log message in the log table after you insert a piece of data into the user table. Of course, the trigger is not only to insert operations, but also to perform modifications, deletions.

Create a Trigger

The syntax for creating a trigger is as follows:

Forupdateupdate 

Where the trigger name parameter refers to the name of the trigger to be created

The Before and after parameters specify the time to trigger execution, either before or after the event

The for every row indicates that the action on any one record satisfies the triggering event and triggers the trigger

To create a trigger with more than one execution statement
TRIGGER trigger name before|  After trigger event for each  ROWBEGIN EXECUTE statement list END      

Where the EXECUTE statement list parameter between Begin and end represents multiple statements that need to be executed, with separate statements separated by semicolons

tips: in general, MySQL defaults to; As an end execution statement, conflicts with the branch required in the trigger

To resolve this issue, you can use the DELIMITER, such as: DELIMITER | |, to turn the end symbol into a | |

When the trigger is created, you can use delimiter to turn the end symbol into;

Mysql> DELIMITER||Mysql>CREATETRIGGER Demo beforeDELETE-On usersForEach ROW-> begin -> insert into logs values (now ()); -> insert into logs Span style= "COLOR: #0000ff" >values (now ()); -> end -> | | query OK, 0 rows affected (0.06 sec) Mysql> DELIMITER;    

The preceding statement, beginning with the end symbol defined as | |, defines a trigger in the middle, once a delete operation satisfies the condition

Executes the statements in begin and end, and then uses the | | End

finally use delimiter; Restore the end symbol

Tigger_event:

The load Data statement inserts the contents of the file into the table, which is equivalent to an INSERT statement, while the Replace statement is generally similar to insert, but if a primary or a unique index exists in the table, If the inserted data is the same as the original primary key or unique, the original data is deleted, and then a new data is added, so sometimes executing a replace statement is equivalent to executing a DELETE and insert statement.

The trigger can be either an SQL statement or multiple blocks of SQL code, how do you create it?

DELIMITER $  #将语句的分隔符改为 $BEGINsql1;sql2;...sqlnEND $DELIMITER;  #将语句的分隔符改回原来的分号 ";"   

At the begin ... The variable can also be defined in the end statement, but only at the begin ... End internal use:

DECLARE var_name Var_type [default value] #定义变量, you can specify the default value SET var_name = value  #给变量赋值

Use of new and old:

Depending on the table above, you can use the appropriate data in the format:

New. ColumnName: A column of data for a new row old.columnname: Deleting a column of data from a row

Say so much now let's create a trigger!

Now there are the following tables:
User Users Table

CREATETABLE' Users ' (' ID 'intOne) unsignedNotNullAuto_increment, ' name 'varchar255)character set utf8mb4  DEFAULT null, ' add_time '  Int (11) default null, primary key  (' id '), key ' name ' (' Name ' (250)) USING BTREE) engine=myisam auto_ Increment=1000001 default charset=latin1;         

Log Logs table:

CREATETABLE' Logs ' (' Id ')int11)not null Auto_increment, ' log ' varchar ( 255) default null COMMENT  " log description  ' primary key (' Id ')) Engine=innodb default charset=utf8mb4 COMMENT = " log table                   

The requirement is that when a piece of data is inserted in the users, a log message is generated in the logs.

To create a trigger:

DELIMITER $CREATETRIGGER User_log AfterINSERTOn usersForEach ROWBEGINDECLARE S1VARCHAR (40) Character Set Utf8;declare s2 varchar ( 20) character Set UTF8, #后面发现中文字符编码出现乱码, set the character set set s2 Span style= "COLOR: #808080" >= "is created"; set s1 = CONCAT (NEW.NAME,S2); The function concat can concatenate strings insert into logs ( log) values (S1);  End $DELIMITER;           

Here I use the navicat:

View trigger SHOW Triggers statement view trigger information

TIP:

Above I use Navicat directly create, if everyone use MySQL front,name here will have a difference, we delete just the trigger, in the MySQL front test
Trigger  User_log; #删除触发器

Open MySQL Front:

MySQL front when compiling sql, you do not have to define the trailing delimiter, and the modified SQL is straightforward:

#DELIMITER $CREATETRIGGER User_log AfterINSERTOn usersForEach ROWBEGINDECLARE S1varchar (40 ) character set UTF8; declare s2 varchar (20) character set UTF8; set s2 = "is created"; set s1 = CONCAT (New.name, S2); #函数CONCAT可以将字符串连接 insert into logs ( log) values (S1);  End #$ #DELIMITER;           

Here's a few more words:

Tips: The SHOW triggers statement cannot query the specified trigger

Viewing trigger information in the Triggers table
From Information_schema.triggers;

The results show the details of all the triggers, and the method can query the details of making the trigger

WHERE trigger_name='user_log';   

tips: All trigger information is stored in the Triggers table under the INFORMATION_SCHEMA database

You can use the SELECT statement to query, if the trigger information is too large, it is best to specify the query through the Trigger_name field

Back up, we created the trigger and continued to insert the data into the users and view the data:

VALUES (' botong-pass ', now ());  

OK, let's check out the logs table again!

From the above example, you can see that only need to insert the user's information in the users, the log will be automatically recorded in the logs table, this is perhaps the trigger to bring me the convenience of it!

Limitations and Precautions

There are two limitations to the trigger:

1. The trigger cannot invoke the stored program that returns the data to the client, nor can it use a dynamic SQL statement with the call statement, but allows the stored program to return the data to the trigger via parameters, that is, if the stored procedure or function returns data to the trigger via an out or inout type parameter, However, the process of returning data directly cannot be called.

2. Statements, such as Start trans-action,commit or rollback, can no longer be used in triggers to start or end transactions in a display or an implicit manner.

Note: The MySQL trigger is executed in the order of the before trigger, row operation, after trigger, in which case the error does not continue to perform the remainder of the operation, if the operation on the transaction table, if an error occurs, then will be rolled back, if it is a non-transactional table operation, Then you cannot roll back, and the data may go wrong.

Summarize

Triggers are triggered based on rows, so deleting, adding, or modifying operations can trigger triggers, so don't write overly complex triggers or add up-to-date triggers, which can have a more serious impact on inserting, modifying, or deleting data, and it can result in poor portability. So when designing a trigger, be sure to consider it.

A trigger is a special kind of stored procedure that triggers execution when inserting, deleting, or modifying data in a particular table, which has finer and more complex data control than the standard functionality of the database itself.

Database triggers have the following effects:

1. Security. You can make a user have some right to manipulate the database based on the value of the database.

# You can limit user actions based on time, such as not allowing database data to be modified after work and holidays.

# You can limit the user's actions based on data in the database, such as not allowing the price of the stock to increase by more than 10% at a time.

2. Audit. You can track user actions on a database.

# Audit the statements of the user operations database.

# writes the user's updates to the database to the audit table.

3. Implementing complex data integrity rules

# implements non-standard data integrity checks and constraints. Triggers can produce more complex restrictions than rules. Unlike rules, triggers can reference columns or database objects. For example, a trigger can rewind any futures that attempt to eat more than their own margin.

# provides a variable default value.

4. Implement complex non-standard database-related integrity rules. Triggers can be used for serial updates of related tables in the database. For example, a delete trigger on the Auths table author_code column causes the corresponding row to be deleted in the other table.

# cascade Modify or delete rows in other tables that match them when modified or deleted.

# Sets the row in the other table to a null value when modified or deleted.

# Sets the row cascade in the other table to be the default value when modified or deleted.

# triggers can reject or rollback changes that disrupt related integrity and cancel transactions that attempt to update data. This trigger works when you insert a foreign key that does not match its primary health. For example, an INSERT trigger can be generated on the Books.author_code column, and if the new value does not match a value in the Auths.author_code column, the insert is rolled back.

5. Synchronously replicates the data in the table in real time.

6. Automatically calculates the data value, if the value of the data meets certain requirements, the specific processing. For example, if the company's account has less than $50,000 in money, it immediately sends warning data to the financial officer.

MySQL flip-flop trigger instance detailed

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.