Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ทำไม MySQL ไม่ให้ insert ตัวอักษร pipe (|) และวิธีแก้ไข


ข้อเท็จจริง

MySQL ไม่มีปัญหากับตัวอักษร pipe (|) ใน string ปกติ ตัวอย่างด้านล่างแสดงว่า insert ได้ปกติ

ตัวอย่างแสดงว่า insert pipe ได้ปกติ

1. สร้างตาราง

mysql> create table PipeInsertDemo 
    -> ( 
    -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    -> UserPassword varchar(100) 
    -> ); 
Query OK, 0 rows affected (0.52 sec)

2. Insert ข้อมูลที่มี pipe

mysql> insert into PipeInsertDemo(UserPassword) values('John123|'); 
Query OK, 1 row affected (0.15 sec)
mysql> insert into PipeInsertDemo(UserPassword) values('|123456CarolTaylor'); 
Query OK, 1 row affected (0.13 sec)
mysql> insert into PipeInsertDemo(UserPassword) values('Adam|345Smith'); 
Query OK, 1 row affected (0.20 sec)

3. ดูข้อมูล - pipe เก็บได้ปกติ

mysql> select * from PipeInsertDemo;
+--------+--------------------+
| UserId | UserPassword       |
+--------+--------------------+
| 1      | John123|           |
| 2      | |123456CarolTaylor |
| 4      | Adam|345Smith      |
+--------+--------------------+

กรณีที่อาจเกิดปัญหา

1. ใช้ใน command line ไม่ได้ escape

mysql -e "INSERT INTO t VALUES ('a|b');"  # shell อาจ interpret pipe

แก้: ใช้ single quote ครอบคำสั่ง SQL หรือ escape ด้วย backslash

2. ใช้ใน LOAD DATA INFILE ที่มี FIELDS TERMINATED BY '|'

ถ้า delimiter เป็น | ข้อมูลที่มี | จะต้อง escape หรือ enclosed by

3. ใช้ใน REPLACE() หรือ string functions บางตัว

pipe เป็นตัวอักษรปกติ ไม่มีความหมายพิเศษใน SQL string

สรุป

MySQL รองรับ pipe (|) ใน string ได้ปกติ ไม่ต้อง escape หากปัญหาเกิดขึ้น มักมาจาก shell/application layer ไม่ใช่ MySQL เอง