Example usage for java.sql Connection getMetaData

List of usage examples for java.sql Connection getMetaData

Introduction

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

Prototype

DatabaseMetaData getMetaData() throws SQLException;

Source Link

Document

Retrieves a DatabaseMetaData object that contains metadata about the database to which this Connection object represents a connection.

Usage

From source file:com.haulmont.cuba.core.sys.dbupdate.DbUpdaterEngine.java

protected String getConnectionUrl(Connection connection) {
    try {//from w ww  . j  a  va 2s  . c om
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        return databaseMetaData.getURL();
    } catch (Throwable e) {
        log.warn("Unable to get connection url");
        return null;
    }
}

From source file:com.jaxio.celerio.configuration.database.support.MetadataExtractor.java

public Metadata extract(JdbcConnectivity jdbcConnectivity, Connection connection)
        throws ClassNotFoundException, SQLException {
    DatabaseMetaData databaseMetadata = connection.getMetaData();
    Metadata metadata = new Metadata();
    metadata.setDatabaseInfo(extractDatabaseInfo(databaseMetadata));
    loadTables(jdbcConnectivity, databaseMetadata, metadata);

    for (Table table : metadata.getTables()) {
        loadColumns(jdbcConnectivity, databaseMetadata, table);
        loadPrimaryKeys(jdbcConnectivity, databaseMetadata, table);
        loadImportedKeys(jdbcConnectivity, databaseMetadata, table, metadata);
        loadIndexes(jdbcConnectivity, databaseMetadata, table);
    }/*from  ww w.j  av  a 2s  .  c  o m*/

    metadata.setJdbcConnectivity(jdbcConnectivity);
    loadEnums(connection, metadata);
    return metadata;
}

From source file:net.certifi.audittablegen.AuditTableGen.java

/**
 * Validates the provided dataSource and gets a DataSourceDMR
 * object to manage database interaction.  Sets initialized flag
 * to true if initialization is successful.
 * @throws SQLException // w w  w .j av a2 s . c  o m
 */
void initialize() throws SQLException {

    Connection connection = dataSource.getConnection();
    //Properties connectionProperties = connection.getClientInfo();
    DatabaseMetaData dmd = connection.getMetaData();

    logger.debug("DatabaseProduct: {}", dmd.getDatabaseProductName());

    try {
        catalog = connection.getCatalog();

        if (schema.isEmpty() || schema == null) {
            try {
                schema = connection.getSchema();
            } catch (AbstractMethodError e) {
                logger.error("Abstract method getSchema() not implemented", e);
                schema = "";
            }
        }
    } catch (SQLException e) {
        logger.error("Error getting catalog/schema", e);

    }

    if (dmd.getDriverName().toLowerCase().contains("postgresql")) {
        dmr = new PostgresqlDMR(dataSource, schema);
        //known dataSource with specific implementation requirements
        //ie PostgrresDMR, HsqldbDMR...            
    } else if (dmd.getDriverName().toLowerCase().contains("hsqldb")) {
        dmr = new HsqldbDMR(dataSource, schema);
        //known dataSource with specific implementation requirements
        //ie PostgrresDMR, HsqldbDMR...            
    } else {
        //generic implementation
        dmr = new GenericDMR(dataSource, schema);
        logger.info("attempting to run against unknown database product");
    }

    if (dmr != null) {
        this.initialized = true;
    }

    if (schema != null && !schema.isEmpty()) {
        dmr.setSchema(schema);

        if (dmr.getSchema() == null) {
            throw new RuntimeException("Schema could not be found.");
        }
    }

}

From source file:it.unibas.spicy.persistence.csv.ExportCSVInstances.java

public void exportCSVInstances(MappingTask mappingTask, String directoryPath, String suffix, int scenarioNo)
        throws DAOException, SQLException, IOException {
    IDataSourceProxy dataSourceTarget = mappingTask.getTargetProxy();
    String folderPath = generateFolderPath(dataSourceTarget.getIntermediateSchema(), directoryPath, suffix, 0);
    //create CSV Folder
    new File(folderPath).mkdir();
    //connection to Postgres
    IConnectionFactory connectionFactory = new SimpleDbConnectionFactory();
    Connection connection = getConnectionToPostgres(connectionFactory);
    try {/*  w w w. j  a  v  a 2 s  .  co m*/
        Statement statement = connection.createStatement();

        //get table names from target database
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String[] tableTypes = new String[] { "TABLE" };

        ResultSet tableResultSet = databaseMetaData.getTables(SpicyEngineConstants.MAPPING_TASK_DB_NAME,
                SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo, null, tableTypes);
        while (tableResultSet.next()) {
            String tableName = tableResultSet.getString("TABLE_NAME");
            createCSVDocument(tableName, SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo, dataSourceTarget,
                    folderPath, statement, null);
        }
    } finally {
        //close connection
        if (connection != null)
            connectionFactory.close(connection);
    }
}

From source file:jp.co.tis.gsp.tools.dba.dialect.Dialect.java

/**
 * ????????????sqlType?/*from   w  w  w .  j  a  v  a  2s. com*/
 * 
 * @param conn ?
 * @param schema 
 * @param tableName ??
 * @param colName ??
 * @return sqlType sqlType
 * @throws SQLException
 */
public int guessType(Connection conn, String schema, String tableName, String colName) throws SQLException {
    if (metaData == null) {
        metaData = conn.getMetaData();
    }

    ResultSet rs = null;
    try {
        rs = metaData.getColumns(null, schema, normalizeTableName(tableName), normalizeColumnName(colName));
        if (!rs.next()) {
            throw new SQLException(tableName + "?" + colName + "????");
        }

        String type = rs.getString("TYPE_NAME");
        if (!isUsableType(type)) {
            System.err.println("[WARN] " + tableName + "." + colName + "  " + type
                    + "???????");
            return UN_USABLE_TYPE;
        }
        return rs.getInt("DATA_TYPE");
    } finally {
        if (rs != null) {
            rs.close();
        }
    }
}

From source file:org.syncope.core.util.ImportExport.java

public void export(final OutputStream os)
        throws SAXException, TransformerConfigurationException, CycleInMultiParentTreeException {

    StreamResult streamResult = new StreamResult(os);
    SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

    TransformerHandler handler = transformerFactory.newTransformerHandler();
    Transformer serializer = handler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(streamResult);//from  w  ww . ja v  a  2s.  c o m
    handler.startDocument();
    handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl());

    Connection conn = DataSourceUtils.getConnection(dataSource);
    ResultSet rs = null;
    try {
        // first read all tables...
        rs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
        Set<String> tableNames = new HashSet<String>();
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            // these tables must be ignored
            if (!tableName.toUpperCase().startsWith("QRTZ_")
                    && !tableName.toUpperCase().equals("ACT_GE_PROPERTY")) {

                tableNames.add(tableName);
            }
        }
        // then sort tables based on foreign keys and dump
        for (String tableName : sortByForeignKeys(conn, tableNames)) {

            doExportTable(handler, conn, tableName);
        }
    } catch (SQLException e) {
        LOG.error("While exporting database content", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing tables result set", e);
            }
        }
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    handler.endElement("", "", ROOT_ELEMENT);
    handler.endDocument();
}

From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java

public DocListEntry getDocsImmediatelyAfter(String checkpoint) {
    DatabaseMetaData dbm = null;//from   w  w w  .jav  a  2s  . c  o  m
    Connection connection = null;

    try {

        connection = ds.getConnection();
        connection.setAutoCommit(true);

        dbm = connection.getMetaData();
        //get the most recent database row after 'checkpoint'
        if (dbm.getDatabaseProductName().equals("MySQL")) {
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            String update_stmt = "select crawl_set,insert_timestamp,UNCOMPRESS(crawl_data) as cdata from "
                    + this.instance_table + " where crawl_set>" + checkpoint + "  LIMIT 1";
            logger.log(Level.FINER, update_stmt);
            ResultSet rs = statement.executeQuery(update_stmt);

            boolean ret_rows = rs.first();

            if (!ret_rows) {
                logger.log(Level.FINER, "No Rows Returned.");
                connection.close();
                return null;
            }
            BigDecimal crawl_set = null;
            String crawl_data = null;
            while (ret_rows) {
                crawl_set = rs.getBigDecimal("crawl_set");
                //crawl_data = rs.getString("crawl_data");
                crawl_data = rs.getString("cdata");
                ret_rows = rs.next();
            }

            rs.close();
            statement.close();
            connection.close();

            //BASE64 DECODE 
            byte[] byte_decoded_entry = org.apache.commons.codec.binary.Base64
                    .decodeBase64(crawl_data.getBytes());
            crawl_data = new String(byte_decoded_entry);

            logger.log(Level.INFO, "Returning from DBStore. Index Value: " + crawl_set.toPlainString());
            logger.log(Level.FINEST, "Returning from DBStore. " + crawl_data);
            DocListEntry dret = new DocListEntry(crawl_set.toPlainString(), crawl_data);
            return dret;
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Unable to retrieve docListEntry " + ex);
    }
    return new DocListEntry(checkpoint, null);
}

From source file:com.norconex.collector.http.db.impl.derby.DerbyCrawlURLDatabase.java

private boolean ensureTablesExist() throws SQLException {
    ArrayListHandler arrayListHandler = new ArrayListHandler();
    Connection conn = datasource.getConnection();
    List<Object[]> tables = arrayListHandler
            .handle(conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" }));
    conn.close();/*from ww w.ja  v  a  2  s .com*/
    if (tables.size() == NUMBER_OF_TABLES) {
        LOG.debug("    Re-using existing tables.");
        return true;
    }
    LOG.debug("    Creating new crawl tables...");
    sqlCreateTable(TABLE_QUEUE);
    sqlCreateTable(TABLE_ACTIVE);
    sqlCreateTable(TABLE_PROCESSED_VALID);
    sqlCreateTable(TABLE_PROCESSED_INVALID);
    sqlCreateTable(TABLE_CACHE);
    sqlCreateTable(TABLE_SITEMAP);
    return false;
}

From source file:org.flywaydb.test.dbunit.DBUnitTestExecutionListener.java

/**
 * Get the dbunit specific database connection
 *
 * @param dataSource/*  w w w.j av a  2 s  .  c om*/
 * @return
 * @throws Exception
 */
protected IDatabaseConnection getConnection(final DataSource dataSource, final TestContext context)
        throws Exception {
    // get connection
    final Connection con = dataSource.getConnection();
    final DatabaseMetaData databaseMetaData = con.getMetaData();
    IDatabaseConnection connection = null;

    try {

        DatabaseConnectionFactory factory = context.getApplicationContext()
                .getBean(DatabaseConnectionFactory.class);

        if (factory != null) {
            dbConnectionFactory = factory;
        }
    } catch (Exception e) {
        logger.debug(String.format("We ignore if we could not find a instance of '%s'",
                DatabaseConnectionFactory.class.getName()));
    }

    if (dbConnectionFactory != null) {
        connection = dbConnectionFactory.createConnection(con, databaseMetaData);
        return connection;
    }
    //      else {
    //         //nnneee
    //         DatabaseConnectionFactory factory = context.getApplicationContext().getBean(DatabaseConnectionFactory.class);
    //         dbConnectionFactory = factory;
    //         connection = dbConnectionFactory.createConnection(con, databaseMetaData);
    //         return connection;
    //      }
    return null;
}