การอัปเดตข้อมูล MySQL จาก Java ควรใช้ PreparedStatement เพื่อป้องกัน SQL Injection และจัดการข้อมูลได้ดี
สร้างตารางตัวอย่าง
mysql> create table DemoTable(
Id int,
FirstName varchar(40) );
Query OK, 0 rows affected (0.62 sec)
เพิ่มข้อมูลตัวอย่าง
mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(111,'Mike'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(121,'Sam'); Query OK, 1 row affected (0.09 sec)
โค้ด Java สำหรับอัปเดตข้อมูล
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class UpdateFromJava {
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 = "update DemoTable set FirstName=? where Id=?";
ps = con.prepareStatement(query);
ps.setString(1, "Tom");
ps.setInt(2, 100);
ps.executeUpdate();
System.out.println("Record is updated successfully......");
} catch (Exception e) {
e.printStackTrace();
} finally {
// ปิด resource
try { if (ps != null) ps.close(); } catch (Exception e) {}
try { if (con != null) con.close(); } catch (Exception e) {}
}
}
}
ผลลัพธ์จากโค้ด Java
Record is updated successfully......
ตรวจสอบข้อมูลหลังอัปเดต
mysql> select * from DemoTable;
+------+-----------+ | Id | FirstName | +------+-----------+ | 100 | Tom | | 111 | Mike | | 121 | Sam | +------+-----------+ 3 rows in set (0.00 sec)
จุดสำคัญของ PreparedStatement
- ป้องกัน SQL Injection - พารามิเตอร์ถูก escape อัตโนมัติ
- ประสิทธิภาพดีกว่า - Query plan ถูก cache และ reuse ได้
- จัดการชนิดข้อมูลอัตโนมัติ - setString, setInt, setDate ฯลฯ
- Batch processing - ใช้
addBatch()และexecuteBatch()สำหรับหลายคำสั่ง
แนวทางปฏิบัติที่ดี (Best Practices)
- ใช้ try-with-resources (Java 7+) เพื่อปิด Connection/Statement อัตโนมัติ
- ใช้ Connection Pool (HikariCP, DBCP) ใน Production
- Externalize config (URL, username, password) ไม่ได้ hardcode
- ใช้ Logging framework แทน System.out.println