Detect if a table exists in Java

Description

The following code shows how to detect if a table exists.

Example


import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
//  ww  w  .j  a  va  2 s .c o m
public class Main {
  public static void main(String[] args) throws Exception {
    Connection connection = getConnection();
    DatabaseMetaData dbm = connection.getMetaData();
    ResultSet rs = dbm.getTables(null, null, "employee", null);
    if (rs.next()) {
      System.out.println("Table exists"); 
    } else {
      System.out.println("Table does not exist"); 
    }
  }

  private static Connection getConnection() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    String url = "jdbc:hsqldb:mem:data/tutorial";

    return DriverManager.getConnection(url, "sa", "");
  }
}




















Home »
  Java Tutorial »
    JDBC »




Batch
Binary Data
Database
Date Time
Insert
ResultSet
SQL
Statement
Stored Function
Table