|
方法是通过查询数据库meta数据来获取数据表。
- public static Boolean doesTableExist(String tablename) {
- Connection con = null;
- HashSet<String> set = new HashSet<String>();
- try {
- Class.forName(DatabaseConnection.getDatabaseConnection());
- con = DriverManager.getConnection(DatabaseName.con);
- DatabaseMetaData meta = con.getMetaData();
- ResultSet res = meta.getTables(null, null, null,
- new String[]{"TABLE"});
- while (res.next()) {
- set.add(res.getString("TABLE_NAME"));
- }
- res.close();
- con.close();
- } catch (Exception e) {
- System.err.println("Exception: " + e.getMessage());
- }
- //System.out.println(set);
- return set.contains(tablename.toUpperCase());
- }
复制代码
其中只需要替换DatabaseConnection.getDatabaseConnection() 和DatabaseName.con 为你需要连接的数据库就好了。可以参考另一篇文章如何连接埠通的数据库:http://blog.csdn.net/autofei/archive/2010/05/24/5621274.aspx
另外一个方法就是尝试连接数据库,然后捕获异常。
- //connection = new DatabaseConnection(DatabaseConnection.DERBY, "", "db", "uncc", "uncc");
- connection = new DatabaseConnection(DatabaseConnection.POSTGRES, "localhost", "postgres",
- "postgres", "postgres");
- database = new Database(connection);
-
- // Checks to see if database structure already exists
- boolean exists = true;
- Statement stmt = connection.getStatement();
- try {
- stmt.executeQuery("SELECT * FROM qgram");
- } catch (Exception e) {
- connection.rollback();
- exists = false;
- }
复制代码
参考:http://www.herongyang.com/jdbc/J ... le-List-Tables.html |
|