Table of Contents
1. Trigger
Concept
2. Trigger operations
Add, delete, and modify operations of triggers
View and delete operations of triggers
3. Transaction
4. Transaction operation
Basic process
Home Database Mysql Tutorial How to apply triggers and transactions in MySQL database

How to apply triggers and transactions in MySQL database

May 28, 2023 pm 04:25 PM
mysql

1. Trigger

Concept

Trigger is a method provided by SQL server to programmers and data analysts to ensure data integrity. It is related to table events. Special stored procedures are triggered by events. Triggers are often used to enforce data integrity constraints and business rules.

2. Trigger operations

Create account and account_log data tables:

CREATE TABLE account(
	id INT PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAR(20),			
	money DOUBL
);
INSERT INTO account VALUES (NULL,'张三',1000),(NULL,'李四',1000);
CREATE TABLE account_log(
	id INT PRIMARY KEY AUTO_INCREMENT,
	operation VARCHAR(20),			
	operation_time DATETIME,		
	operation_id INT,			
	operation_params VARCHAR(200)      
);
Copy after login

Add, delete, and modify operations of triggers

// 语法格式: BEFORE|AFTER    INSERT: 插入 UPDATE:更新  DELETE:删除
// DELIMITER $
// CREATE TRIGGER 触发器名称
// BEFORE|AFTER INSERT|UPDATE|DELETE
// ON 表名
// FOR EACH ROW
// BEGIN
// 	触发器要执行的功能;
// END$
// DELIMITER ;


// 创建INSERT型触发器。用于对account表新增数据进行日志的记录
DELIMITER $

CREATE TRIGGER account_insert
AFTER INSERT
ON account
FOR EACH ROW
BEGIN
	INSERT INTO account_log VALUES (NULL,'INSERT',NOW(),new.id,CONCAT('插入后{id=',new.id,',name=',new.name,',money=',new.money,'}'));
END $

DELIMITER ;

// 向account表添加一条记录
INSERT INTO account VALUES (NULL, '王五', 2000);

// 查询account表
SELECT * FROM account;
Copy after login

View and delete operations of triggers

// 查看标准语法: SHOW TRIGGERS;
// 查看触发器
SHOW TRIGGERS;


// 删除标准语法:DROP TRIGGER 触发器名称;
// 删除account_delete触发器
DROP TRIGGER account_delete;
Copy after login

3. Transaction

Concept

In a relational database, a transaction can be a SQL statement, a group of SQL statements or an entire program . Its characteristic is that this unit either succeeds or fails at the same time, and each SQL statement in the unit depends on each other to form a whole. Transactions should have four attributes: atomicity, consistency, isolation, and durability. These four properties are often called ACID properties.

Four major characteristics:

  • Atomicity: A transaction is an indivisible unit of work. The transaction contains All operations either succeed or fail and are rolled back.

  • Consistency: Transactions must cause the database to change from one consistency state to another consistency state, that is to say, a transaction must be executed before and after execution. in a consistent state.

  • Isolation: When multiple users access the database concurrently, such as when operating the same table, the transaction opened by the database for each user cannot be used by other transactions Interference by operations, multiple concurrent transactions must be isolated from each other

  • Persistence: Once a transaction is submitted, changes to the data in the database It is permanent, and the operation of committing the transaction will not be lost even if the database system encounters a failure.

4. Transaction operation

Basic process

  • ##Open transaction:Record rollback point , and notify the server

  • Execute the SQL statement:Execute one or more specific sql statements

  • End transaction (submit|rollback): Submit: No problem occurs, the data is updated; Rollback: A problem occurs, the data is restored to the state when the transaction was started

Basic operations

-- 开启事务
START TRANSACTION;

-- 执行SQL语句
UPDATE account SET money=money-500 WHERE NAME='张三';

-- 回滚事务(出现问题)
ROLLBACK;

-- 提交事务(没出现问题)
COMMIT;
Copy after login

Transaction submission method

// 查看提交方式
SELECT @@AUTOCOMMIT;  -- 1代表自动提交    0代表手动提交
// 修改事务的提交方式
SET @@autocommit=1;
Copy after login

Transaction isolation level

Four isolation levels

  • Read uncommitted: read uncommitted

  • Read committed: read committed (Oracle/SQL Server database default level )

  • Repeatable read: repeatable read (MySQL default level)

  • Serialization:serializable

may cause problems:

  • Dirty read: refers to a Data in another uncommitted transaction was read during transaction processing, resulting in inconsistent query results.

  • Non-repeatable read: refers to a transaction During the processing, data modified and submitted in another transaction was read, resulting in inconsistent query results.

  • Phantom reading: select whether a certain record exists, The record does not exist. This record was prepared to be inserted, but when the insert was executed, it was found that the record already existed and could not be inserted. Or execute delete deletion, but find that the deletion is successful

Isolation operation

// 查询数据库隔离级别
SELECT @@TX_ISOLATION;

// 修改数据库隔离级别
SET GLOBAL TRANSACTION ISOLATION LEVEL 级别字符串;
Copy after login

Note:The isolation level becomes more and more secure from small to large High, but the efficiency is getting lower and lower, so it is not recommended to use READ UNCOMMITTED and SERIALIZABLE isolation levels.

The above is the detailed content of How to apply triggers and transactions in MySQL database. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

See all articles