Example usage for java.sql DatabaseMetaData getTables

List of usage examples for java.sql DatabaseMetaData getTables

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getTables.

Prototype

ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[])
        throws SQLException;

Source Link

Document

Retrieves a description of the tables available in the given catalog.

Usage

From source file:net.firejack.platform.core.utils.db.DBUtils.java

private static List<Table> getTables(Connection connection, OpenFlameDataSource dataSource)
        throws SQLException {
    List<Table> tableNames = new ArrayList<Table>();
    DatabaseMetaData metaData = connection.getMetaData();
    ResultSet rs;/*  ww w.  ja va  2s.  com*/
    if (dataSource.getName() == DatabaseName.Oracle) {
        rs = metaData.getTables(dataSource.getSid(), dataSource.getSchema(), null, new String[] { "TABLE" });
    } else {
        rs = metaData.getTables(null, null, null, new String[] { "TABLE" });
    }
    while (rs.next()) {
        String tableType = rs.getString("TABLE_TYPE");
        if ("TABLE".equals(tableType)) {
            String tableName = rs.getString("TABLE_NAME");
            Table table = new Table();
            table.setName(tableName);
            List<Column> columns = getColumns(dataSource, metaData, table);
            table.setColumns(columns);
            tableNames.add(table);
        }
    }
    return tableNames;
}

From source file:org.easyrec.utils.spring.store.dao.DaoUtils.java

/**
 * Checks if a given database table is found in the given <code>DataSource</code>.
 *
 * @param dataSource/*from  ww  w. j  av  a2 s.c o  m*/
 * @param tableName
 * @return true if table exists, false if not
 */
public static boolean existsTable(DataSource dataSource, final String tableName) {
    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            ResultSet rs = dbmd.getTables(null, null, tableName, null);
            return rs.next();
        }
    };
    try {
        return (Boolean) JdbcUtils.extractDatabaseMetaData(dataSource, callback);
    } catch (Exception e) {
        throw new RuntimeException("unable to read database metadata", e);
    }
}

From source file:com.jagornet.dhcp.db.DbSchemaManager.java

/**
 * Validate schema.//from w  w  w.ja  v a  2s .c  om
 * 
 * @param dataSource the data source
 * 
 * @throws SQLException if there is a problem with the database
 * @throws IOExcpetion if there is a problem reading the schema file
 * 
 * returns true if database was created, false otherwise
 */
public static boolean validateSchema(DataSource dataSource, String schemaFilename, int schemaVersion)
        throws SQLException, IOException {
    boolean schemaCreated = false;

    List<String> tableNames = new ArrayList<String>();

    Connection conn = dataSource.getConnection();
    DatabaseMetaData dbMetaData = conn.getMetaData();

    log.info("JDBC Connection Info:\n" + "url = " + dbMetaData.getURL() + "\n" + "database = "
            + dbMetaData.getDatabaseProductName() + " " + dbMetaData.getDatabaseProductVersion() + "\n"
            + "driver = " + dbMetaData.getDriverName() + " " + dbMetaData.getDriverVersion());

    String[] types = { "TABLE" };
    ResultSet rs = dbMetaData.getTables(null, null, "%", types);
    if (rs.next()) {
        tableNames.add(rs.getString("TABLE_NAME"));
    } else {
        createSchema(dataSource, schemaFilename);
        dbMetaData = conn.getMetaData();
        rs = dbMetaData.getTables(null, null, "%", types);
        schemaCreated = true;
    }
    while (rs.next()) {
        tableNames.add(rs.getString("TABLE_NAME"));
    }

    String[] schemaTableNames;
    if (schemaVersion <= 1) {
        schemaTableNames = TABLE_NAMES;
    } else {
        schemaTableNames = TABLE_NAMES_V2;
    }

    if (tableNames.size() == schemaTableNames.length) {
        for (int i = 0; i < schemaTableNames.length; i++) {
            if (!tableNames.contains(schemaTableNames[i])) {
                throw new IllegalStateException("Invalid database schema: unknown tables");
            }
        }
    } else {
        throw new IllegalStateException("Invalid database schema: wrong number of tables");
    }

    return schemaCreated;
}

From source file:org.openflexo.technologyadapter.jdbc.util.SQLHelper.java

/**
 * Updates the list of tables for the given schema.
 * //from www  .j  av a2s  .co  m
 * @param schema
 *            the schema
 * @param tables
 *            the table list to update
 * @param factory
 *            the factory used to create the new tables if needed
 */
public static void updateTables(final JDBCSchema schema, List<JDBCTable> tables, final JDBCFactory factory)
        throws SQLException {
    JDBCConnection jdbcConn = schema.getResourceData();
    // TODO : maybe resource leak, cannot use lexical scope for auto-closing
    Connection connection = jdbcConn.getConnection();

    // prepare case ignoring map to match tables
    final Map<String, JDBCTable> sortedTables = new HashMap<>();
    for (JDBCTable table : tables) {
        sortedTables.put(table.getName().toLowerCase(), table);
    }

    // query the tables to find new and removed ones
    final Set<JDBCTable> added = new LinkedHashSet<>();
    final Set<JDBCTable> matched = new LinkedHashSet<>();

    DatabaseMetaData metadata = connection.getMetaData();

    try (ResultSet jdbcTables = metadata.getTables(connection.getCatalog(),
            jdbcConn.getDbType().getSchemaPattern(), "%", null)) {
        while (jdbcTables.next()) {
            String tableName = jdbcTables.getString("TABLE_NAME");

            JDBCTable aTable = sortedTables.get(tableName.toLowerCase());
            if (aTable == null) {
                // new table, add it to the list
                aTable = factory.newInstance(JDBCTable.class);
                aTable.init(schema, tableName);
                added.add(aTable);
            } else {
                matched.add(aTable);
            }
        }
    }
    // gets tables to remove
    Set<JDBCTable> removed = new HashSet<>();
    for (JDBCTable table : tables) {
        if (!matched.contains(table))
            removed.add(table);
    }

    // clears the tables of the removed ones
    // using schema adder and removed fires notifications
    for (JDBCTable table : removed) {
        schema.removeTable(table);
    }
    // adds new tables
    for (JDBCTable table : added) {
        schema.addTable(table);
    }
}

From source file:database.HashTablesTools.java

public static void createTablesIfTheyDontExists(Connection connection, String tableSequenceName,
        String tableFailureName) {

    ResultSet resultTables = null;
    try {// w w w  .j a v a 2 s.  c om

        /**
         DatabaseMetaData dmd = connection.getMetaData();
         ResultSet rs = dmd.getSchemas();
         List<String> schemas = new ArrayList<String>();
         while (rs.next()) {
         schemas.add(rs.getString("TABLE_SCHEM"));
         }
         rs.close();
         System.out.println("Schemas : ");
         for (String schema : schemas) {
         System.out.println(schema);
         }
         */
        // get database metadata
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet rsSchema = metaData.getTables(null, "ME", "%", null);
        List<String> tables = new ArrayList<String>();
        while (rsSchema.next()) {
            tables.add(rsSchema.getString(3)); // 3: table name
        }
        rsSchema.close();

        if (!tables.contains(tableSequenceName.toUpperCase())) {
            System.out.println(tableSequenceName + " dont exist");
            createTables(connection, tableSequenceName, tableFailureName);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

From source file:com.aurel.track.dbase.UpdateDbSchema.java

private static boolean hasTables(Connection conn) {
    boolean hasTables = false;
    try {//ww w . java 2 s. c  o  m
        DatabaseMetaData md = conn.getMetaData();
        String userName = md.getUserName();
        String url = md.getURL();
        boolean isOracleOrDb2 = url.startsWith("jdbc:oracle") || url.startsWith("jdbc:db2");
        ResultSet rsTables = md.getTables(conn.getCatalog(), isOracleOrDb2 ? userName : null, null, null);
        LOGGER.info("Getting the tables metadata");
        if (rsTables != null && rsTables.next()) {
            LOGGER.info("Find TSITE table...");

            while (rsTables.next()) {
                String tableName = rsTables.getString("TABLE_NAME");
                String tablenameUpperCase = tableName.toUpperCase();
                if ("TSITE".equals(tablenameUpperCase)) {
                    LOGGER.info("TSITE table found");
                    hasTables = true;
                    break;
                } else {
                    if (tablenameUpperCase.endsWith("TSITE")) {
                        LOGGER.info(tablenameUpperCase + " table found");
                        hasTables = true;
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    if (!hasTables) {
        Statement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT OBJECTID FROM TSITE");
            if (rs.next()) {
                hasTables = true;
            }
        } catch (SQLException e) {
            LOGGER.info("Table TSITE  does not exist");
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                }
            }
        }
    }
    return hasTables;
}

From source file:org.n52.wps.server.database.PostgresDatabase.java

private static boolean createResultTable() {
    try {//  www . j a  v  a  2 s.co  m
        ResultSet rs;
        DatabaseMetaData meta = PostgresDatabase.conn.getMetaData();
        rs = meta.getTables(null, null, "results", new String[] { "TABLE" });
        if (!rs.next()) {
            LOGGER.info("Table RESULTS does not yet exist.");
            Statement st = PostgresDatabase.conn.createStatement();
            st.executeUpdate(PostgresDatabase.pgCreationString);

            PostgresDatabase.conn.commit();

            meta = PostgresDatabase.conn.getMetaData();

            rs = meta.getTables(null, null, "results", new String[] { "TABLE" });
            if (rs.next()) {
                LOGGER.info("Succesfully created table RESULTS.");
            } else {
                LOGGER.error("Could not create table RESULTS.");
                return false;
            }
        }
    } catch (SQLException e) {
        LOGGER.error("Connection to the Postgres database failed: " + e.getMessage());
        return false;
    }
    return true;
}

From source file:com.stratelia.webactiv.util.DBUtil.java

/**
 * Gets all table names./* w  w  w .  j a v  a  2 s  . c om*/
 * @return
 */
public static Set<String> getAllTableNames() {
    Connection privateConnection = null;
    ResultSet tables_rs = null;
    boolean testingMode = false;
    Set<String> tableNames = new LinkedHashSet<String>();
    try {
        // On ne peux pas utiliser une simple connection du pool
        // on utilise une connection extrieure au contexte transactionnel des ejb
        synchronized (DBUtil.class) {
            if (getInstance().connectionForTest != null) {
                privateConnection = getInstance().connectionForTest;
                testingMode = true;
            } else {
                privateConnection = ConnectionPool.getConnection();
            }
        }

        DatabaseMetaData dbMetaData = privateConnection.getMetaData();
        tables_rs = dbMetaData.getTables(null, null, null, null);
        tables_rs.getMetaData();

        while (tables_rs.next()) {
            tableNames.add(tables_rs.getString(TABLE_NAME));
        }
    } catch (Exception e) {
        SilverTrace.debug("util", "DBUtil.getAllTableNames", "database error ...", e);
    } finally {
        close(tables_rs);
        if (privateConnection != null && !testingMode) {
            close(privateConnection);
        }
    }
    return tableNames;
}

From source file:org.talend.core.model.metadata.builder.database.ExtractMetaDataFromDataBase.java

/**
 * For Hive embedded mode to fetch all tables by "Fake Database Metadata". Notice that you need to setup some
 * configurations by// ww w .ja  va  2 s  .c  om
 * {@link JavaSqlFactory#doHivePreSetup(org.talend.core.model.metadata.builder.connection.Connection)} and then
 * remove these by {@link JavaSqlFactory#doHiveConfigurationClear()}. Added by Marvin Wang on Jan 8, 2013.
 * 
 * @param iMetadataConnection
 * @return
 * @throws SQLException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws ClassNotFoundException
 */
public static List<String> fetchAllTablesForHiveEmbeddedModel(IMetadataConnection iMetadataConnection)
        throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
    List<String> allTables = new ArrayList<String>();
    DatabaseMetaData dbMetaData = HiveConnectionManager.getInstance()
            .extractDatabaseMetaData(iMetadataConnection);
    ResultSet results = dbMetaData.getTables(null, null, "%", new String[] { "TABLE" }); //$NON-NLS-1$//$NON-NLS-2$ 
    while (results.next()) {
        allTables.add(results.getString(3));
    }
    return allTables;
}

From source file:org.wso2.carbon.dataservices.core.script.DSGenerator.java

public static List<String> getTableNamesList(DatabaseMetaData mObject, String dbName, String schema)
        throws SQLException {
    List<String> tableList = new ArrayList<String>();
    ResultSet tableNamesList = mObject.getTables(dbName, schema, null, null);
    while (tableNamesList.next()) {
        tableList.add(tableNamesList.getString(DBConstants.DataServiceGenerator.TABLE_NAME));
    }/*from   ww w . ja va 2s.c o  m*/

    return tableList;
}