Java DataSource checkTableExists(DataSource dataSource, String tableName)

Here you can find the source of checkTableExists(DataSource dataSource, String tableName)

Description

check Table Exists

License

Open Source License

Declaration

public static void checkTableExists(DataSource dataSource, String tableName) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

public class Main {
    public static void checkTableExists(DataSource dataSource, String tableName) throws Exception {
        Connection connection = null;
        try {/*from   w w w.  j a  v  a 2s .c  o m*/
            connection = dataSource.getConnection();
            checkTableExists(connection, tableName);
        } finally {
            closeQuietly(connection);
        }
    }

    public static void checkTableExists(Connection connection, String tableName) throws Exception {
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            statement = connection.createStatement();

            // Check if table exists
            try {
                resultSet = statement.executeQuery("SELECT * FROM " + tableName + " WHERE 1 = 0");
            } catch (Exception e) {
                throw new Exception("Table '" + tableName + "' does not exist");
            }
        } finally {
            closeQuietly(resultSet);
            resultSet = null;
            closeQuietly(statement);
            statement = null;
        }
    }

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

    public static void closeQuietly(Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
            }
        }
    }

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

Related

  1. assertNotNull(DataSource dataSource)
  2. batchExecute(DataSource ds, String sql, Object[]... args)
  3. cleanDB(String ip, DataSource dataSource)
  4. countTable(DataSource dataSource, String tableName)
  5. createDataSource()
  6. createDataTable(DataSource dataSource, String tableName)