MySQL - 更新前触发器



MySQL 触发器分为两种类型:更新前触发器和更新后触发器,用于各种 SQL 操作,例如插入、删除和更新。正如我们在前面章节中已经学习的那样,更新后触发器在数据库表行中的值被更新后立即执行。在这里,让我们进一步了解更新前触发器。

MySQL 更新前触发器

更新前触发器是 MySQL 数据库支持的行级触发器。它是一种特殊的存储过程,在数据库表行中的值被更新之前自动执行。

行级触发器是一种在每次修改行时都会触发的触发器。简单来说,对于在表中进行的每一次事务(例如插入、删除、更新),都会自动执行一个触发器。

每当在数据库中执行 UPDATE 语句时,触发器都会首先被触发,然后才是更新后的值。

语法

以下是创建 MySQL 中更新前触发器的语法:

CREATE TRIGGER trigger_name
BEFORE UPDATE ON table_name FOR EACH ROW
BEGIN
   -- trigger body
END;

示例

让我们首先创建一个名为 USERS 的表,其中包含应用程序用户的详细信息。使用以下 CREATE TABLE 查询来执行此操作:

CREATE TABLE USERS(
   ID INT AUTO_INCREMENT,
   NAME VARCHAR(100) NOT NULL,
   AGE INT NOT NULL,
   birthDATE VARCHAR(100),
   PRIMARY KEY(ID)
);

使用常规 INSERT 语句将值插入 USERS 表中,如下所示:

INSERT INTO USERS (Name, Age, birthDATE) VALUES 
('Sasha', 23, '24/06/1999');
('Alex', 21, '12/01/2001');

USERS 表创建如下:

ID 姓名 年龄 出生日期
1 Sasha 23 24/06/1999
2 Alex 21 12/01/2001

创建触发器

使用以下 CREATE TRIGGER 语句,在 USERS 表上创建一个名为 'before_update_trigger' 的新触发器,使用 SQLSTATE 显示自定义错误,如下所示:

DELIMITER //
CREATE TRIGGER before_update_trigger 
BEFORE UPDATE ON USERS FOR EACH ROW
BEGIN
   IF NEW.AGE < 0 
   THEN SIGNAL SQLSTATE '45000' 
   SET MESSAGE_TEXT = 'Age Cannot be Negative';
END IF;
END //
DELIMITER ;

使用常规 UPDATE 语句更新 USERS 表的值:

UPDATE USERS SET AGE = -1 WHERE NAME = 'Sasha';

输出

此查询的输出将显示一个错误:

ERROR 1644 (45000): Age Cannot be Negative

使用客户端程序的更新前触发器

我们还可以使用客户端程序而不是直接使用 SQL 查询来执行更新前触发器。

语法

要在 PHP 程序中执行更新前触发器,我们需要使用 **mysqli** 函数 **query()** 来执行 CREATE TRIGGER 语句,如下所示:

$sql = "CREATE TRIGGER before_update_trigger BEFORE UPDATE ON SAMPLE FOR EACH ROW
BEGIN
IF NEW.AGE < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Age Cannot be Negative';
END IF;
END";
$mysqli->query($sql);

要在 JavaScript 程序中执行更新前触发器,我们需要使用 **mysql2** 库的 **query()** 函数来执行 CREATE TRIGGER 语句,如下所示:

sql = `CREATE TRIGGER before_update_trigger BEFORE UPDATE ON SAMPLE FOR EACH ROW
BEGIN
IF NEW.AGE < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Age Cannot be Negative';
END IF;
END`;
con.query(sql);  

要在 Java 程序中执行更新前触发器,我们需要使用 **JDBC** 函数 **execute()** 来执行 CREATE TRIGGER 语句,如下所示:

String sql = "CREATE TRIGGER before_update_trigger BEFORE UPDATE ON SAMPLE FOR EACH ROW BEGIN IF NEW.AGE < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Age Cannot be Negative';
END IF;
END";
statement.execute(sql);

要在 Python 程序中执行更新前触发器,我们需要使用 **MySQL Connector/Python** 的 **execute()** 函数来执行 CREATE TRIGGER 语句,如下所示:

beforeUpdate_trigger_query = 'CREATE TRIGGER {trigger_name}
BEFORE UPDATE ON {sample}
FOR EACH ROW
BEGIN
IF NEW.AGE < 0
THEN SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Age Cannot be Negative'
END IF
END'
cursorObj.execute(beforeUpdate_trigger_query)

示例

以下为程序:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$db = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
if($mysqli->connect_errno ) {
   printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf('Connected successfully.
'); $sql = "CREATE TRIGGER before_update_trigger BEFORE UPDATE ON SAMPLE FOR EACH ROW BEGIN IF NEW.AGE < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Age Cannot be Negative'; END IF; END"; if($mysqli->query($sql)){ printf("Trigger created successfully...!\n"); } $q = "UPDATE SAMPLE SET AGE = -1 WHERE NAME = 'Sasha'"; $result = $mysqli->query($q); if ($result == true) { printf("Record updated successfully...!\n"); } if($mysqli->error){ printf("Error message: " , $mysqli->error); } $mysqli->close();

输出

获得的输出如下:

Trigger created successfully...!
PHP Fatal error:  Uncaught mysqli_sql_exception: Age Cannot be Negative
var mysql = require('mysql2');
var con = mysql.createConnection({
host:"localhost",
user:"root",
password:"password"
});

//Connecting to MySQL
con.connect(function(err) {
   if (err) throw err;
    //console.log("Connected successfully...!");
    //console.log("--------------------------");
   sql = "USE TUTORIALS";
   con.query(sql);
   sql = `CREATE TRIGGER before_update_trigger BEFORE UPDATE ON SAMPLE FOR EACH ROW
   BEGIN
   IF NEW.AGE < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Age Cannot be Negative';
   END IF;
   END`;
   con.query(sql);
   console.log("Before Update query executed successfully..!");
   sql = "UPDATE SAMPLE SET AGE = -1 WHERE NAME = 'Sasha'";
   con.query(sql);
   console.log("Table records: ")
   sql = "SELECT * FROM Sample";
   con.query(sql, function(err, result){
      if (err) throw err;
      console.log(result);
   });
});    

输出

产生的输出如下:

Error: Age Cannot be Negative
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class BeforeUpdateTrigger {
    public static void main(String[] args) {
        String url = "jdbc:mysql://127.0.0.1:3306/TUTORIALS";
        String user = "root";
        String password = "password";
        ResultSet rs;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, password);
            Statement st = con.createStatement();
            //System.out.println("Database connected successfully...!");
            String sql = "SELECT * FROM SAMPLE";
            rs = st.executeQuery(sql);
            System.out.println("Sample table records before update: ");
            while(rs.next()) {
                String id = rs.getString("id");
                String name = rs.getString("name");
                String age = rs.getString("age");
                String birth_date = rs.getString("birthDATE");
                System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Birth_date: " + birth_date);
            }
            //lets create trigger on student table
            String sql1 = "CREATE TRIGGER before_update_trigger BEFORE UPDATE ON SAMPLE FOR EACH ROW BEGIN IF NEW.AGE < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Age Cannot be Negative';
            END IF;
            END";
            st.execute(sql1);
            System.out.println("Triggerd Created successfully...!");
            //lets update table records
            String sql3 = "UPDATE SAMPLE SET AGE = -1 WHERE NAME = 'Sasha'";
            st.execute(sql3);
            //let print SAMPLE table records
            String sql4 = "SELECT * FROM SAMPLE";
            rs = st.executeQuery(sql4);
            System.out.println("Sample table records after update: ");
            while(rs.next()) {
                String id = rs.getString("id");
                String name = rs.getString("name");
                String age = rs.getString("age");
                String birth_date = rs.getString("birthDATE");
                System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Birth_date: " + birth_date);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}    

输出

获得的输出如下所示:

Sample table records before update: 
Id: 1, Name: Sasha, Age: 23, Birth_date: 24/06/1999
Id: 2, Name: Alex, Age: 21, Birth_date: 12/01/2001  
import mysql.connector
# Establishing the connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
# Creating a cursor object
cursorObj = connection.cursor()
table_name = 'Sample'
trigger_name = 'before_update_trigger'
beforeUpdate_trigger_query = f'''
CREATE TRIGGER {trigger_name}
BEFORE UPDATE ON {table_name}
FOR EACH ROW
BEGIN
IF NEW.AGE < 0
THEN SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Age Cannot be Negative';
END IF;
END
'''
cursorObj.execute(beforeUpdate_trigger_query)
print(f"BEFORE UPDATE Trigger '{trigger_name}' is created successfully.")
connection.commit()
# Update the "AGE" column
update_query = "UPDATE Sample SET AGE = -1 WHERE NAME = 'Sasha'"
cursorObj.execute(update_query)
print("Update query executed successfully.")
# close the cursor and connection
connection.commit()
cursorObj.close()
connection.close()    

输出

以上代码的输出如下:

BEFORE UPDATE Trigger 'before_update_trigger' is created successfully.
Traceback (most recent call last):
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\connection_cext.py", line 633, in cmd_query
    self._cmysql.query(
_mysql_connector.MySQLInterfaceError: Age Cannot be Negative

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 29, in 
    cursorObj.execute(update_query)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\cursor_cext.py", line 330, in execute
    result = self._cnx.cmd_query(
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\opentelemetry\context_propagation.py", line 77, in wrapper
    return method(cnx, *args, **kwargs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\connection_cext.py", line 641, in cmd_query
    raise get_mysql_exception(
mysql.connector.errors.DatabaseError: 1644 (45000): Age Cannot be Negative
广告