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

วิธีลบตาราง MySQL ด้วย Java (JDBC)

สร้างตารางตัวอย่าง

mysql> create table customerDetails (
    -> CustomerId int,
    -> CustomerName varchar(30)
    -> );
Query OK, 0 rows affected (0.56 sec)

ตรวจสอบตารางที่มีอยู่

mysql> show tables;

ผลลัพธ์ (เห็นตาราง customerdetails):

+------------------------------+
| Tables_in_test3              |
+------------------------------+
| bestdateformatdemo           |
| customerdetails              |
| deletedemo                   |
| ...                          |
+------------------------------+
18 rows in set (0.00 sec)

โค้ด Java สำหรับลบตาราง

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();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ตรวจสอบอีกครั้งหลังลบ

mysql> show tables;

ผลลัพธ์ (ตาราง customerdetails หายไปแล้ว):

+------------------------------+
| Tables_in_test3              |
+------------------------------+
| bestdateformatdemo           |
| deletedemo                   |
| ...                          |
+------------------------------+
17 rows in set (0.00 sec)

คำอธิบายเพิ่มเติม

  • ใช้ DROP TABLE IF EXISTS เพื่อป้องกัน error เมื่อตารางไม่มีอยู่จริง
  • PreparedStatement ใช้ได้กับ DDL เช่น DROP TABLE เช่นกัน
  • ควรปิด PreparedStatement และ Connection ใน finally block หรือใช้ try-with-resources
  • การลบตารางเป็นการกระทำที่ไม่สามารถย้อนกลับได้ (irreversible) ควรระวัง