check Table Or View Exists - Java JDBC

Java examples for JDBC:Table

Description

check Table Or View Exists

Demo Code


//package com.java2s;

import java.sql.Connection;
import java.sql.DatabaseMetaData;

import java.sql.ResultSet;

import java.sql.SQLException;

public class Main {
    public static boolean checkTableOrViewExists(Connection conn,
            String tableName) {/*from  w  ww.  j  a  v a 2s . c  o m*/
        return checkTableExists(conn, tableName)
                || checkViewExists(conn, tableName);
    }

    public static boolean checkTableExists(Connection conn, String tableName) {
        try {
            DatabaseMetaData meta = conn.getMetaData();
            ResultSet rset = meta.getTables(null, null, null,
                    new String[] { "TABLE" });
            while (rset.next()) {
                if (rset.getString("TABLE_NAME")
                        .equalsIgnoreCase(tableName)) {
                    return true;
                }
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
        return false;
    }

    public static boolean checkViewExists(Connection conn, String tableName) {
        try {
            DatabaseMetaData meta = conn.getMetaData();
            ResultSet rset = meta.getTables(null, null, null,
                    new String[] { "VIEW" });
            while (rset.next()) {
                if (rset.getString("TABLE_NAME")
                        .equalsIgnoreCase(tableName)) {
                    return true;
                }
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
        return false;
    }
}

Related Tutorials