Mã Java mẫu
Sử dụng PreparedStatement để cập nhật an toàn, tránh SQL Injection.
1. Tạo bảng MySQL
mysql> create table DemoTable(
Id int,
FirstName varchar(40)
);
Query OK, 0 rows affected (0.62 sec)
2. Chèn dữ liệu ban đầu
mysql> insert into DemoTable values(100,'Chris'); mysql> insert into DemoTable values(111,'Mike'); mysql> insert into DemoTable values(121,'Sam');
3. Mã Java cập nhật
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();
}
}
}
4. Kết quả chạy Java
Record is updated successfully......
5. Kiểm tra lại bảng MySQL
mysql> select * from DemoTable;
+------+-----------+ | Id | FirstName | +------+-----------+ | 100 | Tom | | 111 | Mike | | 121 | Sam | +------+-----------+ 3 rows in set (0.00 sec)
Lưu ý: Luôn đóng Connection, PreparedStatement trong khối finally hoặc dùng try-with-resources (Java 7+).