บทนำ
Java JDBC 提供 DatabaseMetaData インターフェースで、データベースの構造情報(テーブル、カラム、インデックス、主キーなど)をプログラムから取得できます。
ตัวอย่างโค้ด Java: แสดงชื่อตารางทั้งหมดในฐานข้อมูล 'web'
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.DatabaseMetaData;
public class GetDatabaseInformationDemo {
public static void main(String[] args) {
Connection con = null;
try {
// เชื่อมต่อฐานข้อมูล
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/web?useSSL=false",
"root", "123456"
);
// ได้ DatabaseMetaData
DatabaseMetaData metaData = (DatabaseMetaData) con.getMetaData();
// กำหนดประเภทตารางที่ต้องการ (TABLE, VIEW, SYSTEM TABLE, 等)
String[] tableTypes = {"TABLE"};
// ดึงข้อมูลตาราง
ResultSet rs = metaData.getTables(null, null, null, tableTypes);
// แสดงชื่อตาราง (คอลัมน์ที่ 3 = TABLE_NAME)
while (rs.next()) {
System.out.println(rs.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// ปิด Connection
if (con != null) {
try { con.close(); } catch (Exception e) {}
}
}
}
}
ผลลัพธ์ตัวอย่าง
demotable211
demotable212
demotable213
demotable214
demotable215
demotable216
name
select
เมธอดสำคัญของ DatabaseMetaData
| เมธอด | คำอธิบาย |
|---|---|
| getTables(catalog, schema, tableNamePattern, types) | ดึงรายการตาราง/วิว |
| getColumns(catalog, schema, tableNamePattern, columnNamePattern) | ดึงข้อมูลคอลัมน์ |
| getPrimaryKeys(catalog, schema, tableName) | ดึง Primary Key |
| getImportedKeys / getExportedKeys | ดึง Foreign Key |
| getIndexInfo(catalog, schema, tableName, unique, approximate) | ดึงข้อมูล Index |
| getDatabaseProductName() / getDatabaseProductVersion() | ข้อมูล DB Server |
| getDriverName() / getDriverVersion() | ข้อมูล JDBC Driver |
คำแนะนำ
- ใช้
try-with-resources(Java 7+) เพื่อปิด Resource อัตโนมัติ - Pattern รองรับ Wildcard:
%(ทุกตัว),_(ตัวเดียว) nullสำหรับ catalog/schema หมายถึง "ทั้งหมด"