JDBC के साथ MySQL टेबल ड्रॉप करना
Java से MySQL टेबल ड्रॉप करने के लिए PreparedStatement और DROP TABLE IF EXISTS सिंटैक्स का उपयोग करें।
टेबल बनाना और सत्यापित करना
mysql> create table customerDetails (
-> CustomerId int,
-> CustomerName varchar(30)
-> );
Query OK, 0 rows affected (0.56 sec)
mysql> show tables;
आउटपुट में 'customerdetails' टेबल मौजूद है।
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' टेबल नहीं है - सफलतापूर्वक ड्रॉप हो गया।
मुख्य बिंदु
DROP TABLE IF EXISTS- टेबल न होने पर एरर नहीं देताPreparedStatementSQL इंजेक्शन से बचाता हैString.format()से टेबल नाम डायनामिकली पास करें- हमेशा एक्सेप्शन हैंडलिंग करें