检查表是否存在

我有一个embedded数据库的桌面应用程序。 当我执行我的程序时,我需要检查特定的表是否存在,或者如果没有创build。

给定一个名为conn的数据库连接对象,我怎么能检查这个?

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

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中的注意事项。

 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 } 

添加到Gaby的文章中,我的jdbc getTables()for Oracle 10g需要所有大写工作:

"employee" -> "EMPLOYEE"

否则我会得到一个例外:

java.sql.SqlExcepcion用尽了结果集

(即使“员工”在模式中)

我实际上没有发现任何提出的解决scheme是完全完整的,所以我会加我自己的。 这里没有新东西。 你可以从其他提出的解决scheme和各种评论缝合在一起。

至less有两件事你必须确保:

  1. 确保将表名传递给getTables()方法 ,而不是传递空值。 在第一种情况下,您让数据库服务器为您筛选结果,在第二种情况下,您从服务器请求所有表的列表,然后在本地筛选列表。 如果你只search一个表,前者要快得多。

  2. 确保使用等号匹配检查结果集中的表名。 原因是getTables()对表的查询进行模式匹配,而_字符是SQL中的通配符。 假设您正在检查是否存在名为EMPLOYEE_SALARY的表。 然后,你也会在EMPLOYEESSALARY上find一个不符合你想要的。

哦,还记得closures这些结果集。 从Java 7开始,你会想使用try-with-resources语句 。

这是一个完整的解决scheme:

 public static boolean tableExist(Connection conn, String tableName) throws SQLException { boolean tExists = false; try (ResultSet rs = conn.getMetaData().getTables(null, null, tableName, null)) { while (rs.next()) { String tName = rs.getString("TABLE_NAME"); if (tName != null && tName.equals(tableName)) { tExists = true; break; } } } return tExists; } 

你可能想要考虑你的getTables()调用中的types参数(第四个参数)。 通常我会留在null因为你不想限制自己。 VIEW和TABLE一样好,对吗? 现在很多数据库允许你通过一个VIEW来更新,所以在大多数情况下,只限于TABLEtypes,而不是要走的路。 因人而异。

  /** * Method that checks if all tables exist * If a table doesnt exist it creates the table */ public void checkTables() { try { startConn();// method that connects with mysql database String useDatabase = "USE " + getDatabase() + ";"; stmt.executeUpdate(useDatabase); String[] tables = {"Patients", "Procedures", "Payments", "Procedurables"};//thats table names that I need to create if not exists DatabaseMetaData metadata = conn.getMetaData(); for(int i=0; i< tables.length; i++) { ResultSet rs = metadata.getTables(null, null, tables[i], null); if(!rs.next()) { createTable(tables[i]); System.out.println("Table " + tables[i] + " created"); } } } catch(SQLException e) { System.out.println("checkTables() " + e.getMessage()); } closeConn();// Close connection with mysql database }