Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Cách xóa bảng MySQL bằng Java JDBC

Mã Java xóa bảng

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DropTableDemo {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        try {
            con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test3?useSSL=false", "root", "123456");
            ps = con.prepareStatement(
                String.format("DROP TABLE IF EXISTS %s", "customerdetails"));
            boolean result = ps.execute();
            System.out.println("Bảng đã được xóa: " + !result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Giải thích quan trọng

  • DROP TABLE IF EXISTS: Tránh lỗi khi bảng không tồn tại
  • PreparedStatement: Dùng String.format() để truyền tên bảng (không dùng parameter marker cho identifier)
  • ps.execute(): Trả về false cho DDL statements

Kiểm tra trước và sau khi xóa

-- Trước khi xóa
mysql> SHOW TABLES;
+------------------------------+
| Tables_in_test3              |
+------------------------------+
| customerdetails              |
| ... (17 bảng khác)           |
+------------------------------+

-- Sau khi xóa
mysql> SHOW TABLES;
+------------------------------+
| Tables_in_test3              |
+------------------------------+
| ... (17 bảng, KHÔNG có customerdetails) |
+------------------------------+

Lưu ý an toàn: Luôn backup dữ liệu trước khi chạy DROP TABLE trong môi trường production.