如何從 MySQL 資料庫欄位中移除特殊字元?


你可以使用 REPLACE() 函式從資料庫欄位中刪除特殊字元。特殊字元包括雙引號 (“ “)、井號 (#)、美元符號 ($)、百分號 (%) 等。

從資料庫欄位中刪除特殊字元的語法如下。

UPDATE yourTableName
SET yourColumnName=REPLACE(yourColumnName,’yourSpecialCharacters’,’’);

為了理解上述語法,我們建立一張表。建立表的查詢如下

mysql> create table RemoveSpecialCharacterDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> PRIMARY Key(Id)
   -> );
Query OK, 0 rows affected (0.59 sec)

使用插入命令在表中插入一些記錄。查詢如下

mysql> insert into RemoveSpecialCharacterDemo(Name) values('$John');
Query OK, 1 row affected (0.29 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('$Carol');
Query OK, 1 row affected (0.16 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('$Mike');
Query OK, 1 row affected (0.17 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('$Sam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('$Dav$id$');
Query OK, 1 row affected (0.17 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('Robert$');
Query OK, 1 row affected (0.30 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('J$ames$');
Query OK, 1 row affected (0.13 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('Max$well$');
Query OK, 1 row affected (0.27 sec)

使用 select 語句從表中顯示所有記錄。查詢如下

mysql> select *from RemoveSpecialCharacterDemo;

輸出如下

+----+-----------+
| Id | Name      |
+----+-----------+
|  1 | $John     |
|  2 | $Carol    |
|  3 | $Mike     | 
|  4 | $Sam      |
|  5 | $Dav$id$  |
|  6 | Robert$   |
|  7 | J$ames$   |
|  8 | Max$well$ |
+----+-----------+
8 rows in set (0.00 sec)

以下是從資料庫欄位中刪除特殊字元的查詢,使用 REPLACE()。

mysql> update RemoveSpecialCharacterDemo
   -> set Name=replace(Name,'$','');
Query OK, 8 rows affected (0.22 sec)
Rows matched: 8 Changed: 8 Warnings: 0

再次檢查表記錄。顯示所有記錄的查詢如下

mysql> select *from RemoveSpecialCharacterDemo;

輸出如下

+----+---------+
| Id | Name    |
+----+---------+
|  1 | John    |
|  2 | Carol   |
|  3 | Mike    |
|  4 | Sam     |
|  5 | David   |
|  6 | Robert  |
|  7 | James   |
|  8 | Maxwell |
+----+---------+
8 rows in set (0.00 sec)

檢視輸出例項,特殊字元 $ 已從表中完全刪除。

更新於:30-Jul-2019

20K+ 次瀏覽

開啟你的 事業

完成課程以獲得認證

開始
廣告