Example usage for java.sql Connection getCatalog

List of usage examples for java.sql Connection getCatalog

Introduction

In this page you can find the example usage for java.sql Connection getCatalog.

Prototype

String getCatalog() throws SQLException;

Source Link

Document

Retrieves this Connection object's current catalog name.

Usage

From source file:net.antidot.sql.model.core.SQLConnector.java

/**
 * Drop all tables from database with connection c. Specific to MySQL
 * databases./*w  ww. jav  a 2s. c  om*/
 * 
 * @param c
 * @param driver 
 * @throws SQLException
 */
public static void resetMySQLDatabase(Connection c, DriverType driver) throws SQLException {
    // Get tables of database
    DatabaseMetaData meta = c.getMetaData();
    ResultSet tablesSet = meta.getTables(c.getCatalog(), null, "%", null);
    while (tablesSet.next()) {
        // Extract table name
        String tableName = new String(tablesSet.getString("TABLE_NAME"));
        String tableType = tablesSet.getString("TABLE_TYPE");
        // Get a statement from the connection
        Statement stmt = c.createStatement();
        // Execute the query
        if (driver == DriverType.MysqlDriver) {
            // MySQL compatibility
            stmt.execute("SET FOREIGN_KEY_CHECKS = 0");
            stmt.execute("DROP TABLE \"" + tableName + "\"");
        } else {
            if (tableType != null && tableType.equals("TABLE"))
                stmt.execute("DROP TABLE \"" + tableName + "\" CASCADE");
        }
        stmt.close();
    }
}

From source file:at.molindo.dbcopy.Database.java

private static Map<String, Table> readTables(Connection connection) throws SQLException {
    Map<String, Table> tables = new HashMap<String, Table>();

    DatabaseMetaData meta = connection.getMetaData();
    String catalog = connection.getCatalog();

    // for each table in current catalog
    ResultSet rs = meta.getTables(catalog, null, null, null);
    try {/*from w w  w  .jav  a 2s  . co  m*/
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");

            Table.Builder table = Table.builder(tableName);

            // columns
            String columnsQuery = "select COLUMN_NAME,COLLATION_NAME from information_schema.COLUMNS where TABLE_SCHEMA=? and TABLE_NAME=? order by ORDINAL_POSITION";
            Map<String, Column> columns = Utils.executePrepared(connection, columnsQuery, new ColumnHandler(),
                    catalog, tableName);
            if (columns.isEmpty()) {
                throw new IllegalStateException("table (" + tableName + ") without columns?");
            }
            table.addColumns(columns.values());

            // unique keys
            String uniqueKeysQuery = "show keys from `" + tableName + "` in `" + catalog
                    + "` where `Non_unique` = 0 and `Null` = ''";
            List<Map<String, Object>> uniqueKeyColumns = Utils.executePrepared(connection, uniqueKeysQuery,
                    new MapListHandler());
            ListMap<String, Column> uniqeKeys = new ListMap<String, Column>();
            for (Map<String, Object> keyColumn : uniqueKeyColumns) {
                String name = (String) keyColumn.get("INDEX_NAME");
                String columnName = (String) keyColumn.get("COLUMN_NAME");

                if (name == null) {
                    throw new IllegalStateException("KEY_NAME must not be null");
                }
                if (columnName == null) {
                    throw new IllegalStateException("COLUMN_NAME must not be null");
                }

                Column column = columns.get(columnName);
                if (column == null) {
                    throw new IllegalStateException("COLUMN_NAME unknown: " + columnName);
                }

                uniqeKeys.add(name, column);
            }
            for (Map.Entry<String, List<Column>> e : uniqeKeys.entrySet()) {
                table.addUniqueKey(e.getKey(), e.getValue());
            }
            if (uniqeKeys.isEmpty()) {
                log.warn("table without primary key not supported: " + tableName);
            } else {
                tables.put(tableName, table.build());
            }
        }
    } finally {
        Utils.close(rs);
    }

    return tables;
}

From source file:gridool.db.helpers.GridDbUtils.java

public static boolean hasParentTable(@Nonnull final Connection conn, @Nullable final String pkTableName)
        throws SQLException {
    DatabaseMetaData metadata = conn.getMetaData();
    String catalog = conn.getCatalog();
    final ResultSet rs = metadata.getExportedKeys(catalog, null, pkTableName);
    try {//from  ww w.  ja va 2 s .  com
        return rs.next();
    } finally {
        rs.close();
    }
}

From source file:gridool.db.helpers.GridDbUtils.java

/**
 * @return column position is not provided in the returning foreign keys
 *//*from  ww w.j  a v a 2  s .c  o  m*/
@Nonnull
public static Collection<ForeignKey> getExportedKeys(@Nonnull final Connection conn,
        @Nullable final String pkTableName, final boolean setColumnPositions) throws SQLException {
    DatabaseMetaData metadata = conn.getMetaData();
    String catalog = conn.getCatalog();
    final Map<String, ForeignKey> mapping = new HashMap<String, ForeignKey>(4);
    final ResultSet rs = metadata.getExportedKeys(catalog, null, pkTableName);
    try {
        while (rs.next()) {
            final String fkName = rs.getString("FK_NAME");
            ForeignKey fk = mapping.get(fkName);
            if (fk == null) {
                String fkTableName = rs.getString("FKTABLE_NAME");
                fk = new ForeignKey(fkName, fkTableName, pkTableName);
                mapping.put(fkName, fk);
            }
            fk.addColumn(rs, metadata);
        }
    } finally {
        rs.close();
    }
    final Collection<ForeignKey> fkeys = mapping.values();
    if (setColumnPositions) {
        for (ForeignKey fk : fkeys) {
            fk.setColumnPositions(metadata);
        }
    }
    return fkeys;
}

From source file:gridool.db.helpers.GridDbUtils.java

/**
 * @return column position is provided in the returning foreign keys
 *///  w w  w .ja  v  a 2  s  .  com
@Nonnull
public static Collection<ForeignKey> getForeignKeys(@Nonnull final Connection conn,
        @Nullable final String fkTableName, final boolean setColumnPositions) throws SQLException {
    DatabaseMetaData metadata = conn.getMetaData();
    String catalog = conn.getCatalog();
    final Map<String, ForeignKey> mapping = new HashMap<String, ForeignKey>(4);
    final ResultSet rs = metadata.getImportedKeys(catalog, null, fkTableName);
    try {
        while (rs.next()) {
            final String fkName = rs.getString("FK_NAME");
            ForeignKey fk = mapping.get(fkName);
            if (fk == null) {
                //String fkTableName = rs.getString("FKTABLE_NAME");
                String pkTableName = rs.getString("PKTABLE_NAME");
                fk = new ForeignKey(fkName, fkTableName, pkTableName);
                mapping.put(fkName, fk);
            }
            fk.addColumn(rs, metadata);
        }
    } finally {
        rs.close();
    }
    final Collection<ForeignKey> fkeys = mapping.values();
    if (setColumnPositions) {
        for (ForeignKey fk : fkeys) {
            fk.setColumnPositions(metadata);
        }
    }
    return fkeys;
}

From source file:hoot.services.utils.DbUtils.java

/**
 * Drops the postgis render db created for hoot map dataset
 *
 * @param connection//  ww w  .j  a  v  a  2 s.c  om
 *            JDBC Connection
 * @param mapName
 *            map name
 */
public static void deleteRenderDb(Connection connection, String mapName) {
    List<Long> mapIds = getMapIdsByName(connection, mapName);

    if (!mapIds.isEmpty()) {
        long mapId = mapIds.get(0);
        String dbname = null;

        try {
            dbname = connection.getCatalog() + "_renderdb_" + mapId;
        } catch (SQLException e) {
            throw new RuntimeException("Error deleting renderdb for map with id = " + mapId, e);
        }

        try {
            DataDefinitionManager.deleteDb(dbname, false);
        } catch (SQLException e1) {
            logger.warn("Error deleting {} database!", dbname, e1);

            try {
                DataDefinitionManager.deleteDb(connection.getCatalog() + "_renderdb_" + mapName, false);
            } catch (SQLException e2) {
                logger.warn("No renderdb present to delete for {} or map id {}", mapName, mapId, e2);
            }
        }
    }
}

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

private static boolean hasTables(Connection conn) {
    boolean hasTables = false;
    try {//from www  . ja v  a  2s.  c om
        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:gridool.db.helpers.GridDbUtils.java

@Nullable
public static PrimaryKey getPrimaryKey(@Nonnull final Connection conn, @CheckForNull final String pkTableName,
        final boolean reserveAdditionalInfo) throws SQLException {
    if (pkTableName == null) {
        throw new IllegalArgumentException();
    }/*from  www. j a  va  2  s . c  om*/
    DatabaseMetaData metadata = conn.getMetaData();
    String catalog = conn.getCatalog();
    final ResultSet rs = metadata.getPrimaryKeys(catalog, null, pkTableName);
    final PrimaryKey pkey;
    try {
        if (!rs.next()) {
            return null;
        }
        String pkName = rs.getString("PK_NAME");
        pkey = new PrimaryKey(pkName, pkTableName);
        do {
            pkey.addColumn(rs);
        } while (rs.next());
    } finally {
        rs.close();
    }

    if (reserveAdditionalInfo) {
        // set foreign key column positions
        pkey.setColumnPositions(metadata);
        // set exported keys
        final Collection<ForeignKey> exportedKeys = getExportedKeys(conn, pkTableName, false);
        if (!exportedKeys.isEmpty()) {
            final List<String> pkColumnsProbe = pkey.getColumnNames();
            final int numPkColumnsProbe = pkColumnsProbe.size();
            final List<ForeignKey> exportedKeyList = new ArrayList<ForeignKey>(4);
            outer: for (ForeignKey fk : exportedKeys) {
                List<String> names = fk.getPkColumnNames();
                if (names.size() != numPkColumnsProbe) {
                    continue;
                }
                for (String name : names) {
                    if (!pkColumnsProbe.contains(name)) {
                        continue outer;
                    }
                }
                exportedKeyList.add(fk);
            }
            if (!exportedKeyList.isEmpty()) {
                pkey.setExportedKeys(exportedKeyList);
            }
        }
    }
    return pkey;
}

From source file:org.killbill.billing.plugin.dao.PluginDao.java

public PluginDao(final DataSource dataSource, final SQLDialect dialect) throws SQLException {
    this.dataSource = dataSource;
    this.dialect = dialect;

    final String schema;
    Connection connection = null;
    try {//from   w w w  . jav a 2 s. com
        connection = dataSource.getConnection();
        schema = connection.getCatalog();
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
    this.settings = new Settings().withRenderMapping(new RenderMapping()
            .withSchemata(new MappedSchema().withInput(DEFAULT_SCHEMA_NAME).withOutput(schema)));
}

From source file:com.googlecode.flyway.core.dbsupport.mysql.MySQLDbSupport.java

public String getCurrentSchema() {
    return (String) jdbcTemplate.execute(new ConnectionCallback() {
        public String doInConnection(Connection connection) throws SQLException, DataAccessException {
            return connection.getCatalog();
        }//www.  j  a va  2 s.com
    });
}