是否可以使用正則表示式在 MySQL 中強制執行資料檢查?
可以,可以使用正則表示式在 MySQL 中強制執行資料檢查。首先,您需要建立一個表。之後,您需要在表中插入前建立一個觸發器。在這裡,我們將檢查電話號碼的格式。
建立一個表的查詢如下所示
mysql> create table enforceDataUsingRegularExpression - > ( - > yourPhoneNumber varchar(60) - > ); Query OK, 0 rows affected (0.59 sec)
建立一個觸發器的查詢如下所示
mysql> DELIMITER //
mysql> CREATE TRIGGER enforce_phone_check BEFORE INSERT ON enforceDataUsingRegularExpression
- > FOR EACH ROW
- > BEGIN
- > IF (NEW.yourPhoneNumber REGEXP '^(\+?[0-9]{1,4}-)?[0-9]{3,10}$' ) = 0 THEN
- > SIGNAL SQLSTATE '33455'
- > SET MESSAGE_TEXT = 'Your Phone Number is incorrect';
- > END IF;
- > END //
Query OK, 0 rows affected (0.16 sec)
mysql> DELIMITER ;現在,看看使用正則表示式在 MySQL 中強制執行資料檢查時,在表中插入記錄時發生的錯誤
mysql> insert into enforceDataUsingRegularExpression values("+55242-64576");
ERROR 1644 (33455): Your Phone Number is incorrect
mysql> insert into enforceDataUsingRegularExpression values("+76-WD1232221");
ERROR 1644 (33455): Your Phone Number is incorrect
Now inserting the correct data i.e. the correct phone, which is as follows:
mysql> insert into enforceDataUsingRegularExpression values("+55-1232221");
Query OK, 1 row affected (0.13 sec)使用選擇語句顯示錶中的所有記錄。
查詢如下所示
mysql> select *from enforceDataUsingRegularExpression;
以下是輸出
+-----------------+ | yourPhoneNumber | +-----------------+ | +55-1232221 | +-----------------+ 1 row in set (0.00 sec)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP