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.mapd.bench.BenchmarkCloud.java

Connection getConnection(String url, String iUser, String iPasswd) {
    //Open a connection
    logger.debug("Connecting to database url :" + url);
    try {/* w ww. j a va 2 s. c  o m*/
        Connection conn = DriverManager.getConnection(url, iUser, iPasswd);

        targetDBVersion = conn.getMetaData().getDatabaseProductVersion();
        logger.debug("Target DB version is " + targetDBVersion);

        return conn;
    } catch (SQLException ex) {
        logger.error("Exception making connection to " + url + " text is " + ex.getMessage());
        System.exit(2);
    }
    return null;
}

From source file:com.splicemachine.derby.test.framework.SpliceViewWatcher.java

@Override
public void starting(Description description) {
    LOG.trace("Starting");
    Connection connection = null;
    Statement statement = null;/*  ww w  . ja va2  s. c om*/
    ResultSet rs = null;
    try {
        connection = userName == null ? SpliceNetConnection.getConnection()
                : SpliceNetConnection.getConnectionAs(userName, password);
        rs = connection.getMetaData().getTables(null, schemaName, viewName, null);
        if (rs.next()) {
            executeDrop(schemaName, viewName);
        }
        connection.commit();
        statement = connection.createStatement();
        statement.execute(CREATE_VIEW + schemaName + "." + viewName + " " + createString);
        connection.commit();
    } catch (Exception e) {
        LOG.error("Create view statement is invalid ");
        e.printStackTrace(System.err);
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(statement);
        DbUtils.commitAndCloseQuietly(connection);
    }
    super.starting(description);
}

From source file:edu.mayo.informatics.cts.CTSMAPI.refImpl.SQLStatements.java

private SQLStatements(String username, String password, String url, String driver) throws Exception {
    logger_.debug("Initializing sql and sql connections");

    JDBCConnectionDescriptor desc = getConnectionDescriptor();

    try {//from   www .  j  a  va2 s .c o  m
        desc.setDbDriver(driver);
    } catch (ClassNotFoundException e) {
        logger_.error("The driver for your sql connection was not found.  I tried to load " + driver);
        throw e;
    }
    desc.setDbUid(username);
    desc.setDbPwd(password);
    desc.setAutoCommit(true);
    desc.setDbUrl(url);
    desc.setUseUTF8(true);
    desc.setAutoRetryFailedConnections(true);

    //This sets it up to verify that the connection is up and working before a statement
    // is executed, among other things.
    JDBCConnectionPoolPolicy pol = getConnectionPoolPolicy();
    pol.maxActive = 4;
    pol.maxIdle = -1;
    pol.maxWait = -1;
    pol.minEvictableIdleTimeMillis = -1;
    pol.numTestsPerEvictionRun = 1;
    pol.testOnBorrow = false;
    pol.testOnReturn = false;
    pol.testWhileIdle = false;
    pol.timeBetweenEvictionRunsMillis = -1;
    pol.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
    desc.setPingSQL("Select ModelID from Model");

    Connection conn = (Connection) getConnectionPool().borrowObject();

    dbName_ = conn.getMetaData().getDatabaseProductName();

    getConnectionPool().returnObject(conn);

    initStatements();
}

From source file:com.adito.jdbc.DBDumper.java

/**
 * Dump table creation SQL. It is up to the caller to close the stream and connections when
 * finished with.//from  w w  w.jav  a 2 s. co  m
 * 
 * @param writer write SQL to this writer.
 * @param conx connection to get data from
 * @param quoteChar character to use to quote strings
 * @param tables array of table names or <code>null</code> to dump all in
 *        database
 * @throws Exception on any error
 */
public void dumpTable(PrintWriter writer, JDBCConnectionImpl conx, char quoteChar, String[] tables)
        throws Exception {
    Connection jdbcConnection = conx.getConnection();
    DatabaseMetaData dbMetaData = jdbcConnection.getMetaData();

    if (tables == null) {
        ResultSet rs = dbMetaData.getTables(null, null, null, null);
        try {
            while (rs.next()) {
                String tableName = rs.getString("TABLE_NAME");
                String tableType = rs.getString("TABLE_TYPE");
                if (tableType.equalsIgnoreCase("TABLE")) {
                    dumpTable(writer, conx, quoteChar, new String[] { tableName });
                }
            }
        } finally {
            rs.close();
        }
    } else {
        for (int i = 0; i < tables.length; i++) {
            String tableName = tables[i];
            log.info("Dumping table creation for " + tableName);
            writer.println("CREATE TABLE " + tableName + " (");
            boolean first = true;

            // Columns
            ResultSet rs2 = dbMetaData.getColumns(null, null, tableName, "%");
            try {
                while (rs2.next()) {
                    if (first) {
                        first = false;
                    } else {
                        writer.println(",");
                    }
                    String columnName = rs2.getString("COLUMN_NAME");
                    String columnType = rs2.getString("TYPE_NAME");
                    int columnSize = rs2.getInt("COLUMN_SIZE");
                    String nullable = rs2.getString("IS_NULLABLE");
                    String nullString = "NULL";
                    if ("NO".equalsIgnoreCase(nullable)) {
                        nullString = "NOT NULL";
                    }
                    writer.print("    " + columnName + " " + columnType);
                    if (columnSize != 0) {
                        if (columnType.equalsIgnoreCase("varchar") && columnSize > 255) {
                            columnSize = 255;
                        }
                        writer.print(" (" + columnSize + ")");
                    }
                    writer.print(" " + nullString);

                }
            } finally {
                rs2.close();
            }

            // Keys
            try {
                rs2 = dbMetaData.getPrimaryKeys(null, null, tableName);
                String primaryKeyName = null;
                StringBuffer primaryKeyColumns = new StringBuffer();
                while (rs2.next()) {
                    String thisKeyName = rs2.getString("PK_NAME");
                    if ((thisKeyName != null && primaryKeyName == null)
                            || (thisKeyName == null && primaryKeyName != null)
                            || (thisKeyName != null && !thisKeyName.equals(primaryKeyName))
                            || (primaryKeyName != null && !primaryKeyName.equals(thisKeyName))) {
                        if (primaryKeyColumns.length() > 0) {
                            writer.print(",\n    PRIMARY KEY ");
                            if (primaryKeyName != null) {
                                writer.print(primaryKeyName);
                            }
                            writer.print("(" + primaryKeyColumns.toString() + ")");
                        }
                        primaryKeyColumns = new StringBuffer();
                        primaryKeyName = thisKeyName;
                    }
                    if (primaryKeyColumns.length() > 0) {
                        primaryKeyColumns.append(", ");
                    }
                    primaryKeyColumns.append(rs2.getString("COLUMN_NAME"));
                }
                if (primaryKeyColumns.length() > 0) {
                    writer.print(",\n    PRIMARY KEY ");
                    if (primaryKeyName != null) {
                        writer.print(primaryKeyName);
                    }
                    writer.print(" (" + primaryKeyColumns.toString() + ")");
                }
            } finally {
                rs2.close();
            }
            writer.println("\n);");
            writer.println();
        }
    }
}

From source file:com.p6spy.engine.spy.MultipleDataSourceTest.java

private void validateNotSpyEnabled(DataSource ds) throws SQLException {
    assertNotNull("JNDI data source not found", ds);

    // get the connection
    Connection con = ds.getConnection();

    if (ProxyFactory.isProxy(con.getClass())) {
        assertTrue("p6spy proxy is enabled!",
                !(Proxy.getInvocationHandler(con) instanceof P6LogConnectionInvocationHandler));
    }/*from ww w .ja  v  a 2s .c om*/

    if (con.getMetaData().getDatabaseProductName().contains("HSQL")) {
        con.createStatement().execute("set database sql syntax ora true");
    }
    con.createStatement().execute("select current_date from dual");
    assertNull(((P6TestLogger) P6LogQuery.getLogger()).getLastEntry());
}

From source file:com.redsqirl.workflow.utils.jdbc.GenericConfFile.java

public GenericConfFile(String name, Connection conn) throws SQLException {
    dictionaryName = name;//from  w  w w . ja va  2 s  . c o  m

    databaseMetaData = conn.getMetaData();

    typeRecognized = new LinkedHashMap<Integer, FieldType>();
    typeRecognized.put(Types.BOOLEAN, FieldType.BOOLEAN);
    typeRecognized.put(Types.DATE, FieldType.DATETIME);
    typeRecognized.put(Types.TIME, FieldType.DATETIME);
    typeRecognized.put(Types.DOUBLE, FieldType.DOUBLE);
    typeRecognized.put(Types.NUMERIC, FieldType.DOUBLE);
    typeRecognized.put(Types.DECIMAL, FieldType.DOUBLE);
    typeRecognized.put(Types.REAL, FieldType.DOUBLE);
    typeRecognized.put(Types.FLOAT, FieldType.FLOAT);
    typeRecognized.put(Types.INTEGER, FieldType.INT);
    typeRecognized.put(Types.SMALLINT, FieldType.INT);
    typeRecognized.put(Types.TINYINT, FieldType.INT);
    typeRecognized.put(Types.BIGINT, FieldType.LONG);
    typeRecognized.put(Types.VARCHAR, FieldType.STRING);
    typeRecognized.put(Types.CHAR, FieldType.STRING);
    typeRecognized.put(Types.LONGVARCHAR, FieldType.STRING);
    typeRecognized.put(Types.NVARCHAR, FieldType.STRING);
    typeRecognized.put(Types.NCHAR, FieldType.STRING);
    typeRecognized.put(Types.LONGNVARCHAR, FieldType.STRING);
    typeRecognized.put(Types.TIMESTAMP, FieldType.TIMESTAMP);

}

From source file:com.netflix.metacat.connector.snowflake.SnowflakeConnectorTableService.java

/**
 * {@inheritDoc}/*from   w  w  w  .j av  a  2s. c o m*/
 */
@Override
protected ResultSet getTables(@Nonnull @NonNull final Connection connection,
        @Nonnull @NonNull final QualifiedName name, @Nullable final QualifiedName prefix) throws SQLException {
    final String schema = name.getDatabaseName();
    final DatabaseMetaData metaData = connection.getMetaData();
    return prefix == null || StringUtils.isEmpty(prefix.getTableName())
            ? metaData.getTables(connection.getCatalog(), schema, null, TABLE_TYPES)
            : metaData.getTables(connection.getCatalog(), schema,
                    prefix.getTableName() + JdbcConnectorUtils.MULTI_CHARACTER_SEARCH, TABLE_TYPES);
}

From source file:gov.nih.nci.cabig.caaers.CaaersDbTestCase.java

@Override
protected IDataTypeFactory createDataTypeFactory() {
    String productName = ((String) getJdbcTemplate().execute(new ConnectionCallback() {
        public Object doInConnection(Connection con) throws SQLException, DataAccessException {
            return con.getMetaData().getDatabaseProductName();
        }//from  w  ww.  j a  v  a2  s . c o m
    })).toLowerCase();
    if (productName.contains("oracle")) {
        return new OracleDataTypeFactory();
    } else if (productName.contains("hsql")) {
        return new HsqlDataTypeFactory();
    } else {
        return new DefaultDataTypeFactory();
    }
}

From source file:it.unibas.spicy.persistence.json.ExportJsonInstances.java

public void exportJsonInstances(MappingTask mappingTask, String directoryPath, String suffix, int scenarioNo)
        throws DAOException, SQLException, IOException {
    String folderPath = generateFolderPath(mappingTask.getTargetProxy().getIntermediateSchema(), directoryPath,
            suffix, 0);//from   w ww .j a v a  2 s. c  o m
    //create CSV Folder
    new File(folderPath).mkdir();
    //connection to Postgres
    IConnectionFactory connectionFactory = new SimpleDbConnectionFactory();
    Connection connection = getConnectionToPostgres(connectionFactory, scenarioNo);
    try {
        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 + scenarioNo,
                SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo, null, tableTypes);
        while (tableResultSet.next()) {
            String tableName = tableResultSet.getString("TABLE_NAME");
            createJsonDocument(tableName, SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo,
                    mappingTask.getTargetProxy().getIntermediateSchema().getChild(tableName), folderPath,
                    statement);
        }
    } finally {
        //close connection
        if (connection != null)
            connectionFactory.close(connection);
    }
}

From source file:com.qualogy.qafe.business.integration.rdb.SQLQueryDAO.java

/**
 * @param ds//from   w w w  .jav a2s.c o  m
 * @param tableName
 * @throws SQLException
 */
private void populateTableColumnSet(DataSource ds, String tableName) throws SQLException {
    Connection conn = ds.getConnection();
    DatabaseMetaData dbmd = conn.getMetaData();
    ResultSet rsc = dbmd.getColumns(conn.getCatalog(), null, tableName, "%");
    Set<String> foundColumnSet = new HashSet<String>();
    while (rsc.next()) {
        String columnName = rsc.getString("COLUMN_NAME");
        foundColumnSet.add(columnName);
    }
    tableColumnSet.put(tableName, foundColumnSet);
    DataSourceUtils.releaseConnection(conn, ds);
}