Example usage for java.sql ResultSetMetaData getColumnTypeName

List of usage examples for java.sql ResultSetMetaData getColumnTypeName

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnTypeName.

Prototype

String getColumnTypeName(int column) throws SQLException;

Source Link

Document

Retrieves the designated column's database-specific type name.

Usage

From source file:com.abixen.platform.service.businessintelligence.multivisualisation.application.service.JsonFilterService.java

private Map<String, String> getColumnTypeMapping(ResultSetMetaData rsmd) throws SQLException {
    int columnCount = rsmd.getColumnCount();
    Map<String, String> columnTypeMapping = new HashMap<>();

    IntStream.range(1, columnCount + 1).forEach(i -> {
        try {//from   ww w. ja v  a2  s  . c  om
            String columnTypeName = rsmd.getColumnTypeName(i);
            if ("BIGINT".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "INTEGER";
            }
            if ("VARCHAR".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "STRING";
            }
            if ("FLOAT8".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "DOUBLE";
            }
            if ("INT8".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "INTEGER";
            }
            columnTypeMapping.put(rsmd.getColumnName(i).toUpperCase(), columnTypeName.toUpperCase());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    return columnTypeMapping;
}

From source file:org.apache.sqoop.manager.sqlserver.MSSQLTestUtils.java

public void metadataStuff(String table) {
    Connection dbcon = this.getConnection();
    String sql = "select top 1 * from " + table;

    Statement st;//w  w  w.  j  a  v  a 2 s .  co  m
    try {

        st = dbcon.createStatement();
        ResultSet rs = st.executeQuery(sql);
        ResultSetMetaData rsmd = rs.getMetaData();

        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            System.out.println(rsmd.getColumnName(i) + "\t" + rsmd.getColumnClassName(i) + "\t"
                    + rsmd.getColumnType(i) + "\t" + rsmd.getColumnTypeName(i) + "\n");
        }

    } catch (SQLException e) {
        LOG.error(StringUtils.stringifyException(e));
    }

}

From source file:org.apache.hadoop.hive.jdbc.storagehandler.JdbcSerDeHelper.java

public void initialize(Properties tblProps, Configuration sysConf) {
    setProperties(tblProps, sysConf);//from w  ww  .  j  a  va  2 s.com
    StringBuilder colNames = new StringBuilder();
    StringBuilder colTypeNames = new StringBuilder();
    DBConfiguration dbConf = new DBConfiguration(sysConf);
    try {

        dbConnection = dbConf.getConnection();
        String query = getSelectQuery(tblProps);
        Statement st = dbConnection.createStatement();
        ResultSet rs = st.executeQuery(query);
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnsNumber = rsmd.getColumnCount();

        int i = 0;
        for (i = 1; i < columnsNumber; i++) {
            String colName = rsmd.getColumnName(i).replaceAll("\\.", "\\$");
            String colType = rsmd.getColumnTypeName(i);
            colNames.append(colName + ",");
            colTypeNames.append(sqlToHiveColumnTypeNames(colType) + ":");
        }
        colNames.append(rsmd.getColumnName(i).replaceAll("\\.", "\\$"));
        colTypeNames.append(rsmd.getColumnTypeName(i));

        columnNames = colNames.toString();
        columnTypeNames = colTypeNames.toString();

        rs.close();
        st.close();
        dbConnection.close();

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:oscar.form.FrmONAREnhancedRecord.java

private List<String> getColumnNames(String table) throws SQLException {
    List<String> result = new ArrayList<String>();
    ResultSet rs2 = null;// www. j  a v  a 2s  .c  o  m

    try {
        rs2 = DBHandler.GetSQL("select * from " + table + " limit 1");

        ResultSetMetaData md = rs2.getMetaData();

        for (int i = 1; i <= md.getColumnCount(); i++) {
            String name = md.getColumnName(i);
            String type = md.getColumnTypeName(i);
            result.add(name + "|" + type);
        }
    } finally {
        if (rs2 != null)
            rs2.close();
    }

    return result;
}

From source file:cc.osint.graphd.db.SQLDB.java

private JSONObject jsonizeResultSet(ResultSet rs) throws Exception {
    List<JSONObject> results = new ArrayList<JSONObject>();
    ResultSetMetaData md = rs.getMetaData();
    int colmax = md.getColumnCount();
    int i;/*from   www  .java  2  s . c o  m*/
    for (; rs.next();) {
        JSONObject result = new JSONObject();
        for (i = 1; i <= colmax; i++) {
            String colName = md.getColumnName(i).toLowerCase();
            String colClassName = md.getColumnClassName(i);
            String colType = md.getColumnTypeName(i);
            Object obj = rs.getObject(i);
            result.put(colName, obj);
            log.info(colName + ": " + colClassName + ": " + colType + ": " + obj.toString());
        }
        results.add(result);
    }
    JSONObject result = new JSONObject();
    result.put("results", results);
    return result;
}

From source file:jongo.handler.ResultSetMetaDataHandler.java

@Override
public List<Row> handle(ResultSet rs) throws SQLException {
    List<Row> results = new ArrayList<Row>();
    int rowId = 0;
    ResultSetMetaData metaData = rs.getMetaData();
    Map<String, String> map = null;
    for (int i = 1; i <= metaData.getColumnCount(); i++) {
        map = new HashMap<String, String>(2);
        map.put("tableName", metaData.getTableName(i));
        map.put("columnName", metaData.getColumnName(i));
        map.put("columnLabel", metaData.getColumnLabel(i));
        map.put("columnType", metaData.getColumnTypeName(i));
        map.put("columnSize", String.valueOf(metaData.getColumnDisplaySize(i)));
        map.put("precision", String.valueOf(metaData.getPrecision(i)));
        map.put("scale", String.valueOf(metaData.getScale(i)));

        //            map.put("catalog_name", metaData.getCatalogName(i));
        //            map.put("column_class_name", metaData.getColumnClassName(i));
        //            map.put("schema_name", metaData.getSchemaName(i));
        //            map.put("column_type", String.valueOf(metaData.getColumnType(i)));

        if (map != null)
            results.add(new Row(rowId++, map));
    }/* w w  w .  jav a  2 s.c o m*/
    return results;
}

From source file:org.ralasafe.db.DBView.java

private static TableView getTable(Connection conn, String dsName, String schema, String tableName)
        throws SQLException {
    String mySchema = "";
    if (!StringUtil.isEmpty(schema)) {
        mySchema = schema + ".";
    }// www .jav a 2s .c  o m

    if (log.isDebugEnabled()) {
        log.debug("Get table/view definition: dsName=" + dsName + ", table/view Name=" + mySchema + tableName);
    }

    Statement stmt = null;
    ResultSet rs = null;
    ResultSet primaryKeys = null;

    try {
        stmt = conn.createStatement();

        rs = stmt.executeQuery("select * from " + mySchema + tableName + " where 1=2");
        ResultSetMetaData metaData = rs.getMetaData();

        TableView table = new TableView();
        table.setSchema(schema);
        table.setName(tableName);

        DatabaseMetaData metaData2 = conn.getMetaData();
        String databaseProductName = DBUtil.getDatabaseProductName(conn);

        if (databaseProductName == DBUtil.MYSQL) {
            primaryKeys = metaData2.getPrimaryKeys(schema, null, tableName);
        } else {
            primaryKeys = metaData2.getPrimaryKeys(null, null, tableName);
        }

        Map pkColumnViewMap = new HashMap();
        while (primaryKeys.next()) {
            pkColumnViewMap.put(primaryKeys.getString("COLUMN_NAME"), null);
        }

        List columnList = new ArrayList(metaData.getColumnCount());
        for (int i = 1, columnCount = metaData.getColumnCount(); i <= columnCount; i++) {
            ColumnView column = new ColumnView();
            String columnName = metaData.getColumnName(i);
            column.setName(columnName);
            String sqlType = metaData.getColumnTypeName(i);

            if (sqlType.equalsIgnoreCase("blob") || sqlType.equalsIgnoreCase("clob")
                    || sqlType.equalsIgnoreCase("text")) {
                // DO NOTHING
            } else {
                int precision = metaData.getPrecision(i);
                int scale = metaData.getScale(i);

                if (precision != 0) {
                    if (scale == 0) {
                        sqlType = sqlType + "(" + precision + ")";
                    } else {
                        sqlType = sqlType + "(" + precision + "," + scale + ")";
                    }
                }
            }
            column.setSqlType(sqlType);
            columnList.add(column);

            // it's a primary key?
            if (pkColumnViewMap.containsKey(columnName)) {
                pkColumnViewMap.put(columnName, column);
            }
        }

        table.setColumnViews(columnList);

        // sometimes, oracle jdbc driver returns pk info is redundance, 
        // actually the column does exist at all.  Clear them.
        clearInvalidPK(pkColumnViewMap);

        if (pkColumnViewMap.size() > 0) {
            table.setPkColumnViews(pkColumnViewMap.values());
        }
        return table;
    } finally {
        DBUtil.close(primaryKeys);
        DBUtil.close(rs);
        DBUtil.close(stmt);
    }
}

From source file:oscar.form.FrmRecordHelp.java

private Properties getResultsAsProperties(ResultSet rs) throws SQLException {
    Properties p = new Properties();
    ResultSetMetaData md = rs.getMetaData();
    for (int i = 1; i <= md.getColumnCount(); i++) {
        String name = md.getColumnName(i);
        String value;/*  w  ww .  j a v a  2s .com*/

        if (md.getColumnTypeName(i).startsWith("TINY") && md.getScale(i) == 1) {
            if (rs.getInt(i) == 1)
                value = "on";
            else
                value = "off";
        } else if (md.getColumnTypeName(i).equalsIgnoreCase("date"))
            value = UtilDateUtilities.DateToString(rs.getDate(i), _dateFormat);
        else
            value = oscar.Misc.getString(rs, i);

        if (value != null)
            p.setProperty(name, value);
    }

    return (p);
}

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;//from ww w . j  av a2 s . c  o m
    PreparedStatement pst = null;
    try {
        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:oscar.form.FrmRecordHelp.java

public Properties getFormRecord(String sql) //int demographicNo, int existingID)
        throws SQLException {
    Properties props = new Properties();

    ResultSet rs = DBHandler.GetSQL(sql);
    if (rs.next()) {
        ResultSetMetaData md = rs.getMetaData();
        for (int i = 1; i <= md.getColumnCount(); i++) {
            String name = md.getColumnName(i);
            String value;/*from ww  w .j a va 2  s  . c  o  m*/

            if (md.getColumnTypeName(i).startsWith("TINY")) {
                if (rs.getInt(i) == 1)
                    value = "checked='checked'";
                else
                    value = "";
            } else if (md.getColumnTypeName(i).equalsIgnoreCase("date"))
                value = UtilDateUtilities.DateToString(rs.getDate(i), _dateFormat);
            else if (md.getColumnTypeName(i).equalsIgnoreCase("timestamp"))
                value = UtilDateUtilities.DateToString(rs.getTimestamp(i), "yyyy/MM/dd HH:mm:ss");
            else
                value = oscar.Misc.getString(rs, i);

            if (value != null)
                props.setProperty(name, value);
        }
    }
    rs.close();
    return props;
}