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.l2jfree.sql.L2DataSource.java

public final boolean tableExists(String tableName) {
    boolean tableExists = false;

    Connection con = null;
    try {/*from   w w  w  . ja  v  a 2 s  .c o  m*/
        con = getConnection();

        DatabaseMetaData dmd = con.getMetaData();
        final ResultSet rs = dmd.getTables(_database, _schema, tableName, BASE_TABLE);
        {
            tableExists = rs.next();
        }
        rs.close();
    } catch (SQLException e) {
        _log.warn("", e);
        return false;
    } finally {
        L2Database.close(con);
    }

    return tableExists;
}

From source file:org.jtalks.poulpe.util.databasebackup.persistence.DbTableData.java

/**
 * Returns the structure of the table in the shape of list of Table columns.
 * //from w  w w .j av  a2  s  .  c o  m
 * @return A list of Table column elements.
 * @throws SQLException
 *             Is thrown in case any errors during work with database occur.
 */
public List<ColumnMetaData> getStructure() throws SQLException {
    List<ColumnMetaData> tableColumnList = new ArrayList<ColumnMetaData>();
    Statement stmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    Connection connection = null;
    try {
        // Get a list of defaults for the column
        // this cannot be done via ResultSetMetaData, so doing this via tableMetaData instead
        connection = dataSource.getConnection();
        DatabaseMetaData dbMetaData = connection.getMetaData();
        Map<String, String> columnDefaultValues = getColumnDefaults(dbMetaData);

        // Taking the rest of information from ResultSetMetaData object
        stmt = connection.createStatement();
        // WHERE 1 = 0 -- we don't need actual data, just a table structure, so lets make the query's result empty.
        rs = stmt.executeQuery(SELECT_FROM + tableName + " WHERE 1 = 0");
        rsmd = rs.getMetaData();
        int numberOfColumns = rsmd.getColumnCount();

        for (int i = 1; i <= numberOfColumns; i++) {
            tableColumnList.add(getColumnMetaData(rsmd, columnDefaultValues, i));
        }

    } finally {
        if (stmt != null) {
            stmt.close();
        }
        if (connection != null) {
            connection.close();
        }

    }
    return tableColumnList;
}

From source file:gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCUserManagerDAO.java

public boolean validUser(String userName, String password) {
    boolean validUser = false;
    Connection conn = null;
    try {//from ww  w.  j  a v  a 2 s .  c  om
        conn = getDataSource().getConnection(userName, password);

        // The Query below is to make sure connection db is established
        // In some case it was noticed that just making the connection did
        // not make a call to the db

        conn.getMetaData();
        UserEnabledQuery enabledQuery = new UserEnabledQuery((getDataSource()));
        //Check if the user account is enabled
        validUser = ((Boolean) enabledQuery.findObject(userName)).booleanValue();
    } catch (SQLException e) {
        validUser = false;
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception exp) {
        }
    }
    return validUser;
}

From source file:com.thinkbiganalytics.schema.DBSchemaParser.java

private List<Field> listColumns(Connection conn, String schema, String tableName) throws SQLException {
    List<Field> fields;
    Set<String> pkSet = listPrimaryKeys(conn, schema, tableName);
    try (ResultSet columns = conn.getMetaData().getColumns(null, schema, tableName, null)) {
        fields = columnsResultSetToField(columns, pkSet);
    }//from  w ww  .j  av a2 s.c  om
    if (fields.isEmpty()) {
        //if empty try the schema as the catalog (for MySQL db)
        try (ResultSet columns = conn.getMetaData().getColumns(schema, null, tableName, null)) {
            fields = columnsResultSetToField(columns, pkSet);
        }
    }
    return fields;
}

From source file:com.scistor.queryrouter.server.impl.JdbcHandlerImpl.java

@Override
public Map<String, String> queryForMeta(String tableName) {
    long begin = System.currentTimeMillis();
    Map<String, String> result = Maps.newConcurrentMap();
    Connection conn = null;
    PreparedStatement pst = null;
    try {/* www.j  av a2 s .c  o  m*/
        conn = this.getJdbcTemplate().getDataSource().getConnection();
        DatabaseMetaData dbMetaData = conn.getMetaData();
        if (StringUtils.isNotEmpty(tableName)) {
            pst = conn.prepareStatement(String.format("select * from %s where 1=2", tableName));
            ResultSetMetaData rsd = pst.executeQuery().getMetaData();
            for (int i = 0; i < rsd.getColumnCount(); i++) {
                result.put(rsd.getColumnName(i + 1), rsd.getColumnTypeName(i + 1));
            }
        }
    } catch (SQLException e1) {
        logger.error("queryId:{} select meta error:{}", 1, e1.getCause().getMessage());
    } finally {
        JdbcUtils.closeConnection(conn);
        JdbcUtils.closeStatement(pst);
        logger.info("queryId:{} select meta cost:{} ms resultsize:{}", 1, System.currentTimeMillis() - begin,
                result.size());
    }
    return result;
}

From source file:net.sf.jasperreports.engine.query.OracleProcedureCallHandler.java

protected boolean isDataDirectDriver() {
    Connection connection;
    try {//  ww w.java2 s.com
        connection = statement.getConnection();
    } catch (SQLException e) {
        log.error("Failure while detecting driver", e);
        return false;
    }

    DatabaseMetaData metaData = null;
    try {
        metaData = connection.getMetaData();
    } catch (SQLException e) {
        log.error("Failure while detecting driver", e);
    }

    String connectionURL = null;
    if (metaData != null) {
        try {
            connectionURL = metaData.getURL();
        } catch (SQLException e) {
            log.error("Failure while detecting driver", e);
        }
    }

    if (connectionURL != null) {
        if (connectionURL.contains(URL_DATADIRECT) || connectionURL.contains(URL_TIBCO)) {
            return true;
        }
        if (connectionURL.contains(URL_ORACLE)) {
            return false;
        }
    }

    if (ORACLE_CONNECTION_CLASS != null) {
        try {
            if (connection.isWrapperFor(ORACLE_CONNECTION_CLASS)) {
                return false;
            }
        } catch (SQLException e) {
            log.error("Failure while detecting driver", e);
        }
    }

    if (metaData != null) {
        try {
            String driverName = metaData.getDriverName();
            if (driverName.equals(DRIVER_NAME_ORACLE)) {
                return false;
            }
            if (driverName.equals(DRIVER_NAME_DATADIRECT)) {
                return true;
            }
        } catch (SQLException e) {
            log.error("Failure while detecting driver", e);
        }
    }

    //fallback to Oracle
    return false;
}

From source file:com.dbsvg.models.JdbcMainDAO.java

/**
 * Scrubs the database, Generates Pojo Tables with columns, and Primary and
 * Foreign Keys delineated.//from   w  ww  .  j av a2s.co m
 * 
 * @param conn
 *            (null will use the default DB connection Table)
 * @return
 * @throws java.lang.Exception
 */
public Map<String, Table> getTables(Connection conn, String schemaId) throws Exception {
    Map<String, Table> tableMap = new HashMap<String, Table>();
    if (conn == null) {
        conn = getDefaultConnection();
    }
    Statement st = conn.createStatement();
    ResultSet rs = null;
    DatabaseMetaData meta = conn.getMetaData();

    LOG.debug("Grabbing Table Data");
    rs = meta.getTables(null, null, null, new String[] { "TABLE", "VIEW" });
    while (rs.next()) {
        String tableOrViewName = rs.getString("TABLE_NAME");
        Table t = new Table(tableOrViewName);
        tableMap.put(tableOrViewName, t);
        t.setSchemaId(schemaId);
        populateTable(t, conn);
    }

    LOG.debug("Populating Foreign Keys");
    int i = 0;
    for (Table t : tableMap.values()) {
        i++;
        LOG.debug("Checking " + i + " of " + tableMap.size() + "(" + t.getName() + ")");
        checkForForeignKeys(t, meta, conn, tableMap);
        // for (Table fTable: tableMap.values()) {
        // checkForForeignKeys(t, fTable, meta);
        // }
    }

    st.close();
    conn.close();

    return tableMap;
}

From source file:org.grails.orm.hibernate.support.HibernateDialectDetectorFactoryBean.java

public void afterPropertiesSet() throws MetaDataAccessException {
    Assert.notNull(dataSource, "Data source is not set!");
    Assert.notNull(vendorNameDialectMappings, "Vendor name/dialect mappings are not set!");

    Connection connection = null;

    String dbName = (String) JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName");

    try {//  www.ja  v  a2 s. c  om
        connection = DataSourceUtils.getConnection(dataSource);

        try {
            final DialectFactory dialectFactory = createDialectFactory();
            final Connection finalConnection = connection;
            DialectResolutionInfoSource infoSource = new DialectResolutionInfoSource() {
                @Override
                public DialectResolutionInfo getDialectResolutionInfo() {
                    try {
                        return new DatabaseMetaDataDialectResolutionInfoAdapter(finalConnection.getMetaData());
                    } catch (SQLException e) {
                        throw new CouldNotDetermineHibernateDialectException(
                                "Could not determine Hibernate dialect", e);
                    }
                }
            };
            hibernateDialect = dialectFactory.buildDialect(hibernateProperties, infoSource);
            hibernateDialectClassName = hibernateDialect.getClass().getName();
        } catch (HibernateException e) {
            hibernateDialectClassName = vendorNameDialectMappings.getProperty(dbName);
        }

        if (!StringUtils.hasText(hibernateDialectClassName)) {
            throw new CouldNotDetermineHibernateDialectException(
                    "Could not determine Hibernate dialect for database name [" + dbName + "]!");
        }
    } finally {
        DataSourceUtils.releaseConnection(connection, dataSource);
    }
}

From source file:com.bluexml.side.Integration.alfresco.sql.synchronization.schemaManagement.SchemaCreation.java

private void checkMetaData() {
    logger.debug("Checking meta-data");
    DatabaseMetaData dmd = null;//from   w  w w . j a va  2  s . co m

    Connection connection = DataSourceUtils.getConnection(dataSource);

    try {
        dmd = connection.getMetaData();

        String dbname = dmd.getDatabaseProductName();
        String dbversion = dmd.getDatabaseProductVersion();
        if (logger.isDebugEnabled())
            logger.debug("Running sql synchronization on " + dbname + " " + dbversion);

    } catch (SQLException e) {
        logger.error(e);
    } finally {
        DataSourceUtils.releaseConnection(connection, dataSource);
    }
}

From source file:edu.wisc.jmeter.dao.JdbcMonitorDao.java

private void setupTables() {
    final JdbcOperations jdbcOperations = this.jdbcTemplate.getJdbcOperations();

    for (final Map.Entry<String, String> tableConfigEntry : TABLE_CONFIG.entrySet()) {
        jdbcOperations.execute(new ConnectionCallback<Object>() {
            @Override/*w  w  w  . j av a2  s.  c  o m*/
            public Object doInConnection(Connection con) throws SQLException, DataAccessException {
                final DatabaseMetaData metaData = con.getMetaData();

                final String tableName = tableConfigEntry.getKey();
                final ResultSet tables = metaData.getTables(null, null, tableName, null);
                try {
                    if (!tables.next()) {
                        log.warn("'" + tableName + "' table does not exist, creating.");
                        jdbcOperations.update(tableConfigEntry.getValue());
                    } else {
                        log.info("'" + tableName + "' table already exists, skipping.");
                    }
                } finally {
                    tables.close();
                }

                return null;
            }
        });
    }
}