Database table Exists - Java java.sql

Java examples for java.sql:Table

Description

Database table Exists

Demo Code

/*******************************************************************************
 * Copyright (c) 2010 Robert "Unlogic" Olofsson (unlogic@unlogic.se).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v3
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-3.0-standalone.html
 ******************************************************************************/
//package com.java2s;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;

import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
    public static boolean tableExists(DataSource dataSource,
            String tableName) throws SQLException {

        Connection connection = null;
        ResultSet rs = null;//from   w  ww .ja va2s.  c  o m

        try {
            connection = dataSource.getConnection();

            DatabaseMetaData meta = connection.getMetaData();

            rs = meta.getTables(null, null, tableName, null);

            if (rs.next()) {
                return true;
            }
        } finally {
            closeResultSet(rs);
            closeConnection(connection);
        }

        return false;
    }

    public static void closeResultSet(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
        }
    }

    public static void closeConnection(Connection connection) {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
        }
    }
}

Related Tutorials