Java DataSource hasTable(DataSource ds, String table)

Here you can find the source of hasTable(DataSource ds, String table)

Description

Checks if the given database contains a table with the given name.

License

Open Source License

Parameter

Parameter Description
ds DataSource for creating connections to database in question.
table table name, case insensitive.

Exception

Parameter Description
SQLException if there is a problem executing the check.

Return

true if the database contains the table.

Declaration

public static boolean hasTable(DataSource ds, String table) throws SQLException 

Method Source Code

//package com.java2s;

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

import java.sql.ResultSet;

import java.sql.SQLException;

import javax.sql.DataSource;

public class Main {
    /**/*  ww  w. jav a 2s .c  o  m*/
     * Checks if the given database contains a table with the given name.
     * 
     * @param ds DataSource for creating connections to database in question.
     * @param table table name, case insensitive.
     * @return <code>true</code> if the database contains the table.
     * @throws SQLException if there is a problem executing the check.
     */
    public static boolean hasTable(DataSource ds, String table) throws SQLException {
        try (Connection conn = ds.getConnection()) {
            return hasTable(conn, table);
        }
    }

    /**
     * Checks if the given database contains a table with the given name.
     * 
     * @param conn database connection.
     * @param table table name, case insensitive.
     * @return <code>true</code> if the database contains the table.
     * @throws SQLException if there is a problem executing the check.
     */
    public static boolean hasTable(Connection conn, String table) throws SQLException {
        DatabaseMetaData md = conn.getMetaData();
        try (ResultSet tables = md.getTables(null, null, null, null)) {
            boolean result = false;
            while (tables.next()) {
                if (tables.getString("TABLE_NAME").equalsIgnoreCase(table)) {
                    result = true;
                }
            }
            return result;
        }
    }
}

Related

  1. getJNDIConnectionByContainer(String dataSource)
  2. getProductAllCount(DataSource ds, String key, String sql_allcount)
  3. getSchemaSeparator(DataSource dataSource)
  4. getTableColumnCount(DataSource dataSource, String selectedTable)
  5. getTables(DataSource datasource)
  6. initDataSource()
  7. initDatasource(String jndiName)
  8. initDb(DataSource ds)
  9. initializeDataSource()