检查表是否存在

2022-08-31 11:28:33

我有一个嵌入了数据库的桌面应用程序。当我执行我的程序时,我需要检查特定表是否存在,如果没有,请创建它。

给定一个名为conn的数据库的连接对象,我该如何检查?


答案 1
DatabaseMetaData dbm = con.getMetaData();
// check if "employee" table is there
ResultSet tables = dbm.getTables(null, null, "employee", null);
if (tables.next()) {
  // Table exists
}
else {
  // Table does not exist
}

答案 2

您可以使用可用的元数据:

  DatabaseMetaData meta = con.getMetaData();
  ResultSet res = meta.getTables(null, null, "My_Table_Name", 
     new String[] {"TABLE"});
  while (res.next()) {
     System.out.println(
        "   "+res.getString("TABLE_CAT") 
       + ", "+res.getString("TABLE_SCHEM")
       + ", "+res.getString("TABLE_NAME")
       + ", "+res.getString("TABLE_TYPE")
       + ", "+res.getString("REMARKS")); 
  }

有关更多详细信息,请参阅此处。还要注意 JavaDoc 中的注意事项。


推荐