List of usage examples for java.sql DatabaseMetaData getTables
ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[])
throws SQLException;
From source file:org.dspace.storage.rdbms.DatabaseUtils.java
/** * Determine if a particular database table exists in our database * * @param connection// ww w .ja v a 2s . co m * Current Database Connection * @param tableName * The name of the table * @param caseSensitive * When "true", the case of the tableName will not be changed. * When "false, the name may be uppercased or lowercased based on DB type. * @return true if table of that name exists, false otherwise */ public static boolean tableExists(Connection connection, String tableName, boolean caseSensitive) { boolean exists = false; ResultSet results = null; try { // Get the name of the Schema that the DSpace Database is using // (That way we can search the right schema) String schema = getSchemaName(connection); // Get information about our database. DatabaseMetaData meta = connection.getMetaData(); // If this is not a case sensitive search if (!caseSensitive) { // Canonicalize everything to the proper case based on DB type schema = canonicalize(connection, schema); tableName = canonicalize(connection, tableName); } // Search for a table of the given name in our current schema results = meta.getTables(null, schema, tableName, null); if (results != null && results.next()) { exists = true; } } catch (SQLException e) { log.error("Error attempting to determine if table " + tableName + " exists", e); } finally { try { // ensure the ResultSet gets closed if (results != null && !results.isClosed()) results.close(); } catch (SQLException e) { // ignore it } } return exists; }
From source file:com.gmt2001.MySQLStore.java
@Override public boolean FileExists(String fName) { CheckConnection();//w w w .j av a 2 s.c o m fName = validateFname(fName); try (Statement statement = connection.createStatement()) { statement.setQueryTimeout(10); DatabaseMetaData md = connection.getMetaData(); try (ResultSet rs = md.getTables(null, null, "phantombot_" + fName, null)) { return rs.next(); } } catch (SQLException ex) { com.gmt2001.Console.err.printStackTrace(ex); } return false; }
From source file:org.apache.ambari.server.orm.DBAccessorImpl.java
@Override public boolean tableExists(String tableName) throws SQLException { boolean result = false; DatabaseMetaData metaData = getDatabaseMetaData(); ResultSet res = metaData.getTables(null, null, convertObjectName(tableName), new String[] { "TABLE" }); if (res != null) { try {/*from ww w.j ava2s. c om*/ if (res.next()) { return res.getString("TABLE_NAME") != null && res.getString("TABLE_NAME").equalsIgnoreCase(tableName); } } finally { res.close(); } } return result; }
From source file:com.gmt2001.MySQLStore.java
@Override public String[] GetFileList() { CheckConnection();/*ww w.j a v a2 s .co m*/ try (Statement statement = connection.createStatement()) { statement.setQueryTimeout(10); DatabaseMetaData md = connection.getMetaData(); try (ResultSet rs = md.getTables(null, null, "%", null)) { ArrayList<String> s = new ArrayList<>(); while (rs.next()) { s.add(rs.getString(3)); } return s.toArray(new String[s.size()]); } } catch (SQLException ex) { com.gmt2001.Console.err.printStackTrace(ex); } return new String[] {}; }
From source file:org.apache.hadoop.hive.metastore.tools.SchemaToolTaskValidate.java
@VisibleForTesting boolean validateSchemaTables(Connection conn) throws HiveMetaException { System.out.println("Validating metastore schema tables"); String version = null;/* ww w.ja v a 2 s .c om*/ try { MetaStoreConnectionInfo connectionInfo = schemaTool.getConnectionInfo(false); version = schemaTool.getMetaStoreSchemaInfo().getMetaStoreSchemaVersion(connectionInfo); } catch (HiveMetaException he) { System.err.println("Failed to determine schema version from Hive Metastore DB. " + he.getMessage()); System.out.println("Failed in schema table validation."); LOG.debug("Failed to determine schema version from Hive Metastore DB," + he.getMessage(), he); return false; } Connection hmsConn = schemaTool.getConnectionToMetastore(false); LOG.debug("Validating tables in the schema for version " + version); List<String> dbTables = new ArrayList<>(); ResultSet rs = null; try { String schema = null; try { schema = hmsConn.getSchema(); } catch (SQLFeatureNotSupportedException e) { LOG.debug("schema is not supported"); } DatabaseMetaData metadata = conn.getMetaData(); rs = metadata.getTables(null, schema, "%", new String[] { "TABLE" }); while (rs.next()) { String table = rs.getString("TABLE_NAME"); dbTables.add(table.toLowerCase()); LOG.debug("Found table " + table + " in HMS dbstore"); } } catch (SQLException e) { throw new HiveMetaException("Failed to retrieve schema tables from Hive Metastore DB," + e.getMessage(), e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { throw new HiveMetaException("Failed to close resultset", e); } } } // parse the schema file to determine the tables that are expected to exist // we are using oracle schema because it is simpler to parse, no quotes or backticks etc List<String> schemaTables = new ArrayList<>(); List<String> subScripts = new ArrayList<>(); String baseDir = new File(schemaTool.getMetaStoreSchemaInfo().getMetaStoreScriptDir()).getParent(); String schemaFile = new File(schemaTool.getMetaStoreSchemaInfo().getMetaStoreScriptDir(), schemaTool.getMetaStoreSchemaInfo().generateInitFileName(version)).getPath(); try { LOG.debug("Parsing schema script " + schemaFile); subScripts.addAll(findCreateTable(schemaFile, schemaTables)); while (subScripts.size() > 0) { schemaFile = baseDir + "/" + schemaTool.getDbType() + "/" + subScripts.remove(0); LOG.debug("Parsing subscript " + schemaFile); subScripts.addAll(findCreateTable(schemaFile, schemaTables)); } } catch (Exception e) { System.err.println("Exception in parsing schema file. Cause:" + e.getMessage()); System.out.println("Failed in schema table validation."); return false; } LOG.debug("Schema tables:[ " + Arrays.toString(schemaTables.toArray()) + " ]"); LOG.debug("DB tables:[ " + Arrays.toString(dbTables.toArray()) + " ]"); // now diff the lists schemaTables.removeAll(dbTables); if (schemaTables.size() > 0) { Collections.sort(schemaTables); System.err.println("Table(s) [ " + Arrays.toString(schemaTables.toArray()) + " ] " + "are missing from the metastore database schema."); System.out.println("[FAIL]\n"); return false; } else { System.out.println("[SUCCESS]\n"); return true; } }
From source file:fr.cnes.sitools.datasource.jdbc.business.SitoolsSQLDataSource.java
/** * Return the list of tables in the database * /*from www . ja va 2 s .c om*/ * @param schemaPattern * the schema pattern to access tables * @return the list of table names */ public List<Table> getTables(String schemaPattern) { String schema = (schemaPattern == null) ? schemaOnConnection : schemaPattern; // Oracle : pour supprimer le caractre vide dans chaine if (null == schema || schema.equals("")) { schema = null; } ArrayList<Table> tables = new ArrayList<Table>(); Connection conn = null; ResultSet rs = null; try { conn = getConnection(); DatabaseMetaData metaData = conn.getMetaData(); rs = metaData.getTables(null, schema, null, new String[] { "TABLE", "VIEW" }); while (rs.next()) { tables.add(new Table(rs.getString("TABLE_NAME"), rs.getString("TABLE_SCHEM"))); } } catch (SQLException ex) { LOG.log(Level.SEVERE, null, ex); } finally { closeConnection(conn); closeResultSet(rs); } return tables; }
From source file:org.springframework.jdbc.core.metadata.GenericTableMetaDataProvider.java
/** * Method supporting the metadata processing for a table. *//*w ww .j av a 2s. c o m*/ private void locateTableAndProcessMetaData(DatabaseMetaData databaseMetaData, @Nullable String catalogName, @Nullable String schemaName, @Nullable String tableName) { Map<String, TableMetaData> tableMeta = new HashMap<>(); ResultSet tables = null; try { tables = databaseMetaData.getTables(catalogNameToUse(catalogName), schemaNameToUse(schemaName), tableNameToUse(tableName), null); while (tables != null && tables.next()) { TableMetaData tmd = new TableMetaData(); tmd.setCatalogName(tables.getString("TABLE_CAT")); tmd.setSchemaName(tables.getString("TABLE_SCHEM")); tmd.setTableName(tables.getString("TABLE_NAME")); if (tmd.getSchemaName() == null) { tableMeta.put(this.userName != null ? this.userName.toUpperCase() : "", tmd); } else { tableMeta.put(tmd.getSchemaName().toUpperCase(), tmd); } } } catch (SQLException ex) { if (logger.isWarnEnabled()) { logger.warn("Error while accessing table meta data results: " + ex.getMessage()); } } finally { JdbcUtils.closeResultSet(tables); } if (tableMeta.isEmpty()) { if (logger.isWarnEnabled()) { logger.warn( "Unable to locate table meta data for '" + tableName + "': column names must be provided"); } } else { processTableColumns(databaseMetaData, findTableMetaData(schemaName, tableName, tableMeta)); } }
From source file:org.efaps.db.databases.MySQLDatabase.java
/** * <p>This is the MySQL specific implementation of an all deletion. * Following order is used to remove all eFaps specific information: * <ul>//ww w. j a v a 2s . co m * <li>remove all views of the user</li> * <li>remove all tables of the user</li> * <li>remove all sequences of the user</li> * </ul></p> * <p>The table are dropped with cascade, so all depending sequences etc. * are also dropped automatically. </p> * <p>Attention! If application specific tables, views or constraints are * defined, this database objects are also removed!</p> * * @param _con sql connection * @throws SQLException on error while executing sql statements */ @Override @SuppressFBWarnings("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE") public void deleteAll(final Connection _con) throws SQLException { final Statement stmtSel = _con.createStatement(); final Statement stmtExec = _con.createStatement(); try { if (MySQLDatabase.LOG.isInfoEnabled()) { MySQLDatabase.LOG.info("Remove all Tables"); } final DatabaseMetaData metaData = _con.getMetaData(); // delete all views final ResultSet rsViews = metaData.getTables(null, null, "%", new String[] { "VIEW" }); while (rsViews.next()) { final String viewName = rsViews.getString("TABLE_NAME"); if (MySQLDatabase.LOG.isDebugEnabled()) { MySQLDatabase.LOG.debug(" - View '" + viewName + "'"); } stmtExec.execute("drop view " + viewName); } rsViews.close(); // delete all constraints final ResultSet rsTables = metaData.getTables(null, null, "%", new String[] { "TABLE" }); while (rsTables.next()) { final String tableName = rsTables.getString("TABLE_NAME"); final ResultSet rsf = _con.getMetaData().getImportedKeys(null, null, tableName); while (rsf.next()) { final String fkName = rsf.getString("FK_NAME").toUpperCase(); if (MySQLDatabase.LOG.isDebugEnabled()) { MySQLDatabase.LOG.debug(" - Foreign Key '" + fkName + "'"); } stmtExec.execute("alter table " + tableName + " drop foreign key " + fkName); } } // delete all tables rsTables.beforeFirst(); while (rsTables.next()) { final String tableName = rsTables.getString("TABLE_NAME"); if (MySQLDatabase.LOG.isDebugEnabled()) { MySQLDatabase.LOG.debug(" - Table '" + tableName + "'"); } stmtExec.execute("drop table " + tableName + " cascade"); } rsTables.close(); } finally { stmtSel.close(); stmtExec.close(); } }
From source file:org.apache.torque.generator.source.jdbc.JdbcMetadataSource.java
/** * Get all the table names in the current database that are not * system tables./*from w ww. j a v a 2s . c om*/ * * @param dbMeta JDBC database metadata. * @return The list of all the tables in a database. * @throws SQLException */ List<String> getTableNames(DatabaseMetaData dbMeta, String dbSchema) throws SQLException { log.debug("Getting table list..."); List<String> tables = new ArrayList<String>(); ResultSet tableNames = null; // these are the entity types we want from the database String[] types = { "TABLE", "VIEW" }; try { tableNames = dbMeta.getTables(null, dbSchema, "%", types); while (tableNames.next()) { String name = tableNames.getString(TABLE_NAME_POS_IN_TABLE_METADATA); tables.add(name); } } finally { if (tableNames != null) { tableNames.close(); } } return tables; }
From source file:au.edu.jcu.fascinator.plugin.harvester.directory.DerbyCache.java
/** * Check if the given table exists in the database. * //from www . ja v a2s .c o m * @param table The table to look for * @return boolean flag if the table was found or not * @throws SQLException if there was an error accessing the database */ private boolean findTable(String table) throws SQLException { boolean tableFound = false; DatabaseMetaData meta = connection().getMetaData(); ResultSet result = meta.getTables(null, null, null, null); while (result.next() && !tableFound) { if (result.getString("TABLE_NAME").equalsIgnoreCase(table)) { tableFound = true; } } close(result); return tableFound; }