Example usage for java.sql DatabaseMetaData getColumns

List of usage examples for java.sql DatabaseMetaData getColumns

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getColumns.

Prototype

ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern)
        throws SQLException;

Source Link

Document

Retrieves a description of table columns available in the specified catalog.

Usage

From source file:org.apache.cayenne.dbsync.reverse.dbload.AttributeLoader.java

protected ResultSet getResultSet(String catalogName, String schemaName, DatabaseMetaData metaData)
        throws SQLException {
    return metaData.getColumns(catalogName, schemaName, WILDCARD, WILDCARD);
}

From source file:org.obiba.runtime.upgrade.support.DatabaseMetadataUtil.java

/**
 * Indicates whether the specified table contains the specified column.
 *
 * @param tableName the table name//from   w ww .  j  av a2 s . com
 * @param columnName the column name
 * @return <code>true</code> if the column exists in the table
 */
public boolean hasColumn(final String tableName, final String columnName) {
    boolean columnPresent = false;

    try {
        columnPresent = (Boolean) JdbcUtils.extractDatabaseMetaData(dataSource, new DatabaseMetaDataCallback() {
            @Override
            public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
                return dbmd.getColumns(null, null, tableName, columnName).next();
            }
        });
    } catch (MetaDataAccessException ex) {
        throw new RuntimeException(ex);
    }

    return columnPresent;
}

From source file:com.pactera.edg.am.metamanager.extractor.dao.impl.TargetDBInfoDaoImpl.java

private int getColumnSize(DatabaseMetaData metaData, String schema, String table, String column)
        throws SQLException {
    ResultSet rs = metaData.getColumns(null, schema, table, column);
    int columnSize = -1;
    while (rs.next()) {
        columnSize = rs.getInt(Column.COLUMN_SIZE) / 3;
    }/*from w w w. j  a v  a2s.c o m*/
    rs.close();
    return columnSize;
}

From source file:org.wte4j.impl.service.SimpleDbViewModelService.java

@Override
public Map<String, Class<?>> listModelElements(Class<?> inputClass, Map<String, String> properties) {
    Map<String, Class<?>> elements = new HashMap<String, Class<?>>();
    String viewName = properties.get(VIEW_NAME);
    Connection connection = null;
    ResultSet rs = null;/*ww w .j av a 2s . c  om*/
    try {
        try {
            connection = ds.getConnection();
            DatabaseMetaData metaData = ds.getConnection().getMetaData();
            rs = metaData.getColumns(null, null, viewName, null);

            while (rs.next()) {
                String columnName = rs.getString("COLUMN_NAME").toLowerCase();
                Class<?> type = MapperSqlType.map(rs.getInt("DATA_TYPE"));
                elements.put(columnName, type);
            }

        } finally {
            if (rs != null) {
                rs.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    } catch (SQLException e) {
        throw new WteException("error in view " + viewName, e);
    }
    return elements;
}

From source file:com.emergya.persistenceGeo.dbutils.DatabaseUtilsImpl.java

@Override
public List<String> getTableColumns(String tableName) {
    ResultSet rs = null;//  w w w . j a va 2s.c  o m
    List<String> result = new ArrayList<String>();
    try {
        Connection con = ds.getConnection();
        DatabaseMetaData md = con.getMetaData();
        rs = md.getColumns(null, null, tableName, null);
        while (rs.next()) {
            result.add(rs.getString("COLUMN_NAME"));
        }
        con.close();

    } catch (SQLException e) {
        throw new DbUtilsException("Error changing column names", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();

            } catch (SQLException e) {
                throw new DbUtilsException("Error accessing database", e);
            }
        }
    }
    return result;
}

From source file:com.emergya.persistenceGeo.dbutils.DatabaseUtilsImpl.java

public String getColumnType(String tableName, String columnName) {
    ResultSet rs = null;//ww  w. j a  v  a 2s . c o m
    String result = null;
    try {
        Connection con = ds.getConnection();
        DatabaseMetaData md = con.getMetaData();
        rs = md.getColumns(null, null, tableName, columnName);
        int i = 0;
        while (rs.next()) {
            i++;
            result = rs.getString("TYPE_NAME");
            if (i > 1) {
                throw new DbUtilsException(
                        "Found more than one column when looking for column's type. [tableName=" + tableName
                                + ", columnName=" + columnName + "]");
            }
        }
        con.close();

    } catch (SQLException e) {
        throw new DbUtilsException("Error getting type of column", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new DbUtilsException("Error accessing database", e);
            }
        }
    }
    return result;
}

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

/**
 * Get List of ColumnDef objects for all tables
 * in the targeted database/schema.  Postgres specific code replaces 
 * 'serial' date type with integer, because the column in the audit table
 * must be of type integer and not serial.  Since this data is interpreted
 * by ChangeSourceFactory, which should be database independent, the
 * translation needs to be in the DMR./*from   w  w w . j  a v a  2s  . c  o  m*/
 * 
 * @param tableName
 * @return ArrayList of ColumnDef objects or an empty list if none are found.
 */
@Override
public List getColumns(String tableName) {

    //getDataTypes will initialize the map if it isn't already loaded
    Map<String, DataTypeDef> dtds = getDataTypes();

    List columns = new ArrayList<>();

    try {
        Connection conn = dataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        ResultSet rs = dmd.getColumns(null, verifiedSchema, tableName, null);

        //load all of the metadata in the result set into a map for each column

        ResultSetMetaData rsmd = rs.getMetaData();
        int metaDataColumnCount = rsmd.getColumnCount();
        if (!rs.isBeforeFirst()) {
            throw new RuntimeException(
                    "No results for DatabaseMetaData.getColumns(" + verifiedSchema + "." + tableName + ")");
        }
        while (rs.next()) {
            ColumnDef columnDef = new ColumnDef();
            Map columnMetaData = new CaseInsensitiveMap();
            for (int i = 1; i <= metaDataColumnCount; i++) {
                columnMetaData.put(rsmd.getColumnName(i), rs.getString(i));
            }
            columnDef.setName(rs.getString("COLUMN_NAME"));

            String type_name = rs.getString("TYPE_NAME");
            if (type_name.equalsIgnoreCase("serial")) {
                columnDef.setTypeName("int4");
            } else {
                columnDef.setTypeName(type_name);
            }
            columnDef.setSqlType(rs.getInt("DATA_TYPE"));
            columnDef.setSize(rs.getInt("COLUMN_SIZE"));
            columnDef.setDecimalSize(rs.getInt("DECIMAL_DIGITS"));
            columnDef.setSourceMeta(columnMetaData);

            if (dtds.containsKey(columnDef.getTypeName())) {
                columnDef.setDataTypeDef(dtds.get(columnDef.getTypeName()));
            } else {
                throw new RuntimeException(
                        "Missing DATA_TYPE definition for data type " + columnDef.getTypeName());
            }
            columns.add(columnDef);
        }

    } catch (SQLException e) {
        throw Throwables.propagate(e);
    }

    return columns;

}

From source file:org.wso2.carbon.reporting.template.core.client.DatasourceClient.java

/**
 * retrieves the meta data about the column names in the given table and dsname
 *
 * @param dsName    name of the data source
 * @param tableName name of the table in the data source
 * @return HashMap of column_name (key) and type_of_column (value)
 * @throws ReportingException will occurred if any sql syntax problem found.
 *//*w  w  w  .j a v  a  2  s.  com*/
public HashMap<String, String> getMetaData(String dsName, String tableName) throws ReportingException {
    HashMap<String, String> metaData = new HashMap<String, String>();
    Connection connection = getConnection(dsName);
    try {
        DatabaseMetaData dBMetaData = connection.getMetaData();
        ResultSet resultSet = dBMetaData.getColumns(null, null, tableName, null);
        while (resultSet.next()) {
            metaData.put(resultSet.getString("COLUMN_NAME").toLowerCase(), resultSet.getString("TYPE_NAME"));
        }
        return metaData;
    } catch (SQLException e) {
        log.error("Error while retrieving the meta data of Table: " + tableName + " from DB :" + dsName);
        throw new ReportingException(
                "Error while retrieving the meta data of Table: " + tableName + " from DB :" + dsName);
    }

}

From source file:com.clican.pluto.orm.tool.TableMetadata.java

private void initColumns(DatabaseMetaData meta) throws SQLException {
    ResultSet rs = null;/*from  w w w .  j  ava2  s  . c om*/

    try {
        rs = meta.getColumns(catalog, schema, name, "%");
        while (rs.next())
            addColumn(rs);
    } finally {
        if (rs != null)
            rs.close();
    }
}

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

/**
 * Grabs all the Columns and fills them with the information from the JDBC.
 * Also detects Primary keys/*  ww  w.jav a2 s.  co  m*/
 * 
 * @param table
 * @param conn
 * @return
 * @throws java.lang.Exception
 */
private Table populateTable(Table table, Connection conn) throws Exception {

    int maxWidth = 0;

    maxWidth = (int) (table.getName().length() * 1.5);

    DatabaseMetaData meta = conn.getMetaData();
    ResultSet rs = meta.getColumns(null, null, table.getName(), null);

    while (rs.next()) {
        String columnName = rs.getString("COLUMN_NAME");
        if (columnName.length() > maxWidth)
            maxWidth = columnName.length();
        Column c = new ColumnObject(columnName);
        table.getColumns().put(columnName, c);
        c.setTable(table);
        populateColumn(c, rs);
    }

    table.setWidth(CHAR_WIDTH * maxWidth + PAD_WIDTH);
    table.setHeight(CHAR_HEIGHT * table.getColumns().size() + PAD_HEIGHT);

    try {
        rs = meta.getPrimaryKeys(null, null, table.getName());

        while (rs.next()) {
            String columnName = rs.getString("COLUMN_NAME");
            PrimaryKey pk = table.getColumns().get(columnName).transformToPK();
            table.getColumns().put(columnName, pk);
            table.getPrimaryKeys().put(columnName, pk);
        }
    } catch (Exception e) {
        LOG.error(table.getName() + " Has Primary Key Issues.", e);
    }
    rs.close();

    return table;
}