เมื่อใช้ JDBC เขียนข้อมูลลง MySQL ควรใช้ PreparedStatement แทน Statement ธรรมดา เพื่อป้องกัน SQL Injection และจัดการตัวอักษรพิเศษ (รวมถึง Backslash \) ได้อัตโนมัติ
สร้างตารางทดสอบ
mysql> create table DemoTable1904 ( ClientId int, ClientName varchar(20), ClientAge int ); Query OK, 0 rows affected (0.00 sec)
โค้ด Java ใช้ PreparedStatement
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class EscapeBackslashesDemo {
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/web?" + "useSSL=false",
"root", "123456"
);
String query = "insert into DemoTable1904(ClientId,ClientName,ClientAge) values(?,?,?)";
ps = con.prepareStatement(query);
ps.setInt(1, 1001);
ps.setString(2, "David Miller");
ps.setInt(3, 35);
ps.executeUpdate();
System.out.println("One row is inserted.....");
} catch (Exception e) {
e.printStackTrace();
}
}
}
ผลลัพธ์การรัน

ตรวจสอบข้อมูลในฐานข้อมูล
mysql> select * from DemoTable1904;
+----------+--------------+-----------+ | ClientId | ClientName | ClientAge | +----------+--------------+-----------+ | 1001 | David Miller | 35 | +----------+--------------+-----------+ 1 row in set (0.00 sec)
ทำไม PreparedStatement จึงดีกว่า?
| ลักษณะ | Statement (concat string) | PreparedStatement |
|---|---|---|
| SQL Injection | เสี่ยงสูง | ปลอดภัย (Parameterized) |
| Backslash/Quote | ต้อง Escape เอง | จัดการอัตโนมัติ |
| Performance | Compile ทุกครั้ง | Pre-compile ใช้ซ้ำได้ |
| Batch Insert | ยาก | รองรับ addBatch() |
การ Escape แบบ Manual (ถ้าต้องใช้ Statement)
String escaped = original.replace("\\", "\\\\").replace("'", "\\'");
สรุป: ใช้ PreparedStatement และ setString() / setInt() เป็น Best Practice สำหรับ JDBC ทั้งเรื่องความปลอดภัย Backslash handling และ Performance