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

INSERT ข้อมูลที่มี Double Quotes ใน MySQL (Escape ด้วย Backslash)

จัดเก็บ Double Quotes ตรงตัวใน MySQL: Escape ด้วย Backslash

ใน String Literal ของ MySQL (อยู่ใน Single Quotes) ให้ Escape Double Quotes ด้วย \\\"

ไวยากรณ์

INSERT INTO your_table VALUES('\\"your_value\\"');

สร้างตารางและข้อมูล

mysql> CREATE TABLE DemoTable (Name VARCHAR(20));
Query OK, 0 rows affected (0.63 sec)

mysql> INSERT INTO DemoTable VALUES('\\"John\\"'), ('\\"Chris\\"'), ('\\"Adam Smith\\"'), ('\\"Carol\\"');
Query OK, 4 rows affected

ผลลัพธ์: Double Quotes เป็นส่วนหนึ่งของข้อมูล

+--------------+
| Name         |
+--------------+
| "John"       |
| "Chris"      |
| "Adam Smith" |
| "Carol"      |
+--------------+

Escape Sequences ใน MySQL String Literals

วิธีอื่น: ใช้ Single Quotes ครอบ String ที่มี Double Quotes

-- ใส่ Double Quotes ใน Single Quotes ได้เลย (ไม่ต้อง Escape)
INSERT INTO DemoTable VALUES('"John"');
-- แต่ถ้ามี Single Quotes ในข้อมูล ต้อง Escape: 'O\\'Neil'

⚠️ SQL Mode: NO_BACKSLASH_ESCAPES

หาก SQL Mode มี NO_BACKSLASH_ESCAPES Backslash ไม่ทำหน้าที่ Escape

-- ต้อง Double Escape หรือใช้วิธีอื่น
INSERT INTO DemoTable VALUES('\\\\"John\\\\"');  -- Double backslash
-- หรือ
SET SESSION sql_mode = REPLACE(@@sql_mode, 'NO_BACKSLASH_ESCAPES', '');

Prepared Statements (Parameterized Queries) - แนะนำสำหรับ Application

-- ไม่ต้อง Escape เอง Driver จัดการให้
PreparedStatement ps = conn.prepareStatement("INSERT INTO DemoTable VALUES(?)");
ps.setString(1, "\"John\"");  // Java: Escape ด้วย Backslash ใน String Literal
ps.executeUpdate();
Sequenceความหมาย
\\0NUL (ASCII 0)
\\'Single Quote
\\"Double Quote
\\bBackspace
\\nNewline (Line Feed)
\\rCarriage Return
\\tTab
\\ZCtrl+Z (Windows EOF)
\\\\Backslash ตรงตัว
\\%% ตรงตัว (ใน LIKE)
\\__ ตรงตัว (ใน LIKE)