Example usage for java.sql ResultSetMetaData getColumnLabel

List of usage examples for java.sql ResultSetMetaData getColumnLabel

Introduction

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

Prototype

String getColumnLabel(int column) throws SQLException;

Source Link

Document

Gets the designated column's suggested title for use in printouts and displays.

Usage

From source file:moe.yuna.palinuridae.core.BaseDao.java

/**
 * @param sql//from  w w  w. j  a  v  a 2 s .co m
 * @param list
 * @return
 * @throws DBUtilException
 */
public List<Map<String, Object>> select(final String sql, final List<Object> list) throws DBUtilException {
    return getJdbcTemplate().query(sql, (stat) -> {
        for (int i = 0; i < list.size(); i++) {
            stat.setObject(i + 1, list.get(i));
        }
    }, (DBCallable<List<Map<String, Object>>>) (rs) -> {
        ResultSetMetaData md = rs.getMetaData();
        List<Map<String, Object>> rlist = new ArrayList<>();
        while (rs.next()) {
            Map<String, Object> map = new HashMap<String, Object>();
            for (int i = 1; i <= md.getColumnCount(); i++) {
                //                    map.put(md.getColumnName(i), rs.getObject(i));
                map.put(md.getColumnLabel(i), rs.getObject(i));
            }
            rlist.add(map);
        }
        return rlist;
    });
}

From source file:org.apache.kylin.rest.adhoc.AdHocRunnerJdbcImpl.java

@Override
public void executeQuery(String query, List<List<String>> results, List<SelectedColumnMeta> columnMetas)
        throws Exception {
    Statement statement = null;//from w  ww .ja va 2s . com
    Connection connection = this.getConnection();
    ResultSet resultSet = null;

    try {
        statement = connection.createStatement();
        resultSet = statement.executeQuery(query);
        extractResults(resultSet, results);
    } catch (SQLException sqlException) {
        throw sqlException;
    }

    //extract column metadata
    ResultSetMetaData metaData = null;
    int columnCount = 0;
    try {
        metaData = resultSet.getMetaData();
        columnCount = metaData.getColumnCount();

        // fill in selected column meta
        for (int i = 1; i <= columnCount; ++i) {
            columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i),
                    false, metaData.isCurrency(i), metaData.isNullable(i), false,
                    metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i),
                    null, null, null, metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i),
                    metaData.getColumnTypeName(i), metaData.isReadOnly(i), false, false));
        }

    } catch (SQLException sqlException) {
        throw sqlException;
    }

    closeConnection(connection);
}

From source file:org.apache.hadoop.sqoop.manager.SqlManager.java

@Override
public Map<String, Integer> getColumnTypes(String tableName) {
    String stmt = "SELECT t.* FROM " + tableName + " AS t WHERE 1 = 1";

    ResultSet results = execute(stmt);
    if (null == results) {
        return null;
    }//w  w  w  .jav a2  s.  c  o  m

    try {
        Map<String, Integer> colTypes = new HashMap<String, Integer>();

        int cols = results.getMetaData().getColumnCount();
        ResultSetMetaData metadata = results.getMetaData();
        for (int i = 1; i < cols + 1; i++) {
            int typeId = metadata.getColumnType(i);
            String colName = metadata.getColumnName(i);
            if (colName == null || colName.equals("")) {
                colName = metadata.getColumnLabel(i);
            }

            colTypes.put(colName, Integer.valueOf(typeId));
        }

        return colTypes;
    } catch (SQLException sqlException) {
        LOG.error("Error reading from database: " + sqlException.toString());
        return null;
    }
}

From source file:com.izv.controlador.ControladorAndroid.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww w .  ja va  2  s. co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    boolean forward = false;
    String target, op, action, view;
    ControlDB bd;

    target = request.getParameter("target");
    op = request.getParameter("op");
    action = request.getParameter("action");
    if (target.equals("inmobiliaria") && op.equals("insert") && action.equals("op")) {
        response.setContentType("text/html;charset=UTF-8");
        format = new SimpleDateFormat();
        format.applyPattern("yyyy-dd-MM");
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        format.format(date);
        Inmueble inmueble = new Inmueble();
        inmueble.setLocalidad(request.getParameter("localidad"));
        inmueble.setDireccion(request.getParameter("direccion"));
        inmueble.setTipo(request.getParameter("tipo"));
        inmueble.setUsuario(request.getParameter("usuario"));
        inmueble.setPrecio(request.getParameter("precio"));
        inmueble.setFechaalta(date);
        ModeloInmueble.insert(inmueble);
        Inmueble inm = ModeloInmueble.get(inmueble.getId() + "");
        try (PrintWriter out = response.getWriter()) {
            out.println(inm.getId() + "");
        }
    } else {
        if (target.equals("inmobiliaria") && op.equals("imagen") && action.equals("op")) {
            forward = false;
            boolean error = false;
            String id = request.getParameter("id");
            response.setContentType("text/html;charset=UTF-8");
            Calendar calendario = new GregorianCalendar();
            Date date = calendario.getTime();
            SimpleDateFormat formatoFecha = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSSSS");
            String fecha = formatoFecha.format(date);
            String titulo = "inmueble_" + id + "_" + fecha;
            Part archivoPost = request.getPart("archivo");
            String carpeta = getServletContext().getRealPath("/") + "fotos/";
            InputStream input = archivoPost.getInputStream();
            try {
                OutputStream out = new FileOutputStream(carpeta + titulo + ".jpg");
                byte[] b = new byte[2048];
                int length;
                while ((length = input.read(b)) != -1) {
                    out.write(b, 0, length);
                }
            } catch (Exception e) {
                error = true;
            } finally {
                input.close();
            }
            Fotos fot = new Fotos();
            fot.setIdinmueble(Integer.valueOf(id));
            fot.setNombre(titulo + ".jpg");
            ModeloFoto.insert(fot);
            try (PrintWriter out = response.getWriter()) {
                if (error) {
                    out.println("error");
                } else {
                    out.println("foto subida"); // respuesta json chapucera
                }
            }
        } else {
            if (target.equals("bar")) {
                try {
                    bd = new ControlDB();
                    bd.cargarDriver();
                    bd.conectar();
                    response.setContentType("application/json");
                    /*
                     int r = bd.ejecutarDelete("delete from pedidos where idPedido=52");
                     System.out.println(r);
                     */
                    //                        String fechaHora = getFecha();
                    //                        String consulta = "insert into pedidos values(0, '" + fechaHora + "', 0, 0, null, 'admin ', 6, 1)";
                    //                        bd.ejecutarInsert(consulta);
                    ResultSet r = bd.ejecutarSelect("Select * from pedidos");
                    JSONArray array = new JSONArray();
                    ResultSetMetaData rsMetaData = r.getMetaData();
                    int columns = rsMetaData.getColumnCount();
                    try {
                        while (r.next()) {
                            JSONObject objetoJSON = new JSONObject();
                            for (int i = 1; i <= columns; i++) {
                                objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i));
                            }
                            System.out.println(objetoJSON + "\n");
                            //                                System.out.println(r.getString(1) + " " + r.getString(2) + " " + r.getString(3)
                            //                                        + " " + r.getString(4));
                            array.put(objetoJSON);
                        }
                    } catch (SQLException ex) {
                        Logger.getLogger(ControladorAndroid.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    PrintWriter out = response.getWriter();
                    out.print(array);
                    out.flush();
                    //                        obj.put("nombre", "Angel");
                    //                        obj.put("password", "1234");
                    //                        System.out.println("JSON " + obj.toString());
                    //                        System.out.println(obj.getString("nombre") + " " + obj.getString("password"));

                } catch (JSONException ex) {
                    Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(ControladorAndroid.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }
    }
}

From source file:org.hsweb.ezorm.rdb.executor.AbstractJdbcSqlExecutor.java

@Override
public <T> T single(SQL sql, ObjectWrapper<T> wrapper) throws SQLException {
    if (sql instanceof EmptySQL)
        return null;
    SQLInfo info = compileSql(sql);//  w w w  .  j  a va2 s  .c om
    printSql(info);
    Connection connection = getConnection();
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    T data = null;
    try {
        statement = connection.prepareStatement(info.getSql());
        //?
        this.preparedParam(statement, info);
        resultSet = statement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int count = metaData.getColumnCount();
        List<String> headers = new ArrayList<>();
        for (int i = 1; i <= count; i++) {
            headers.add(metaData.getColumnLabel(i));
        }
        wrapper.setUp(headers);
        int index = 0;
        if (resultSet.next()) {
            data = wrapper.newInstance();
            for (int i = 0; i < headers.size(); i++) {
                Object value = resultSet.getObject(i + 1);
                wrapper.wrapper(data, index, headers.get(i), value);
            }
            index++;
            wrapper.done(data);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("<==      total: {}", index);
        }
    } finally {
        closeResultSet(resultSet);
        closeStatement(statement);
        releaseConnection(connection);
    }
    return data;
}

From source file:com.thinkbiganalytics.hive.service.HiveService.java

public QueryResult query(String query) throws DataAccessException {
    final DefaultQueryResult queryResult = new DefaultQueryResult(query);
    final List<QueryResultColumn> columns = new ArrayList<>();
    final Map<String, Integer> displayNameMap = new HashMap<>();
    if (query != null && !query.toLowerCase().startsWith("show")) {
        query = safeQuery(query);// w  ww  . j a  va2  s  . c  om
    }
    try {
        //  Setting in order to query complex formats like parquet
        jdbcTemplate.execute("set hive.optimize.index.filter=false");
        jdbcTemplate.query(query, new RowMapper<Map<String, Object>>() {
            @Override
            public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
                if (columns.isEmpty()) {
                    ResultSetMetaData rsMetaData = rs.getMetaData();
                    for (int i = 1; i <= rsMetaData.getColumnCount(); i++) {
                        String colName = rsMetaData.getColumnName(i);
                        DefaultQueryResultColumn column = new DefaultQueryResultColumn();
                        column.setField(rsMetaData.getColumnName(i));
                        String displayName = rsMetaData.getColumnLabel(i);
                        column.setHiveColumnLabel(displayName);
                        //remove the table name if it exists
                        displayName = StringUtils.substringAfterLast(displayName, ".");
                        Integer count = 0;
                        if (displayNameMap.containsKey(displayName)) {
                            count = displayNameMap.get(displayName);
                            count++;
                        }
                        displayNameMap.put(displayName, count);
                        column.setDisplayName(displayName + "" + (count > 0 ? count : ""));

                        column.setTableName(StringUtils.substringAfterLast(rsMetaData.getColumnName(i), "."));
                        column.setDataType(ParserHelper.sqlTypeToHiveType(rsMetaData.getColumnType(i)));
                        columns.add(column);
                    }
                    queryResult.setColumns(columns);
                }
                Map<String, Object> row = new LinkedHashMap<>();
                for (QueryResultColumn column : columns) {
                    row.put(column.getDisplayName(), rs.getObject(column.getHiveColumnLabel()));
                }
                queryResult.addRow(row);
                return row;
            }
        });

    } catch (DataAccessException dae) {
        dae.printStackTrace();
        throw dae;
    }
    return queryResult;

}

From source file:com.jaeksoft.searchlib.crawler.database.DatabaseCrawlSql.java

public String checkSqlSelect()
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
    JDBCConnection jdbcCnx = getNewJdbcConnection();
    Transaction transaction = null;//w  w w .  j  a v  a  2 s  .  co m
    StringWriter sw = null;
    PrintWriter pw = null;
    try {
        sw = new StringWriter();
        pw = new PrintWriter(sw);
        transaction = getNewTransaction(jdbcCnx);
        Query query = transaction.prepare(sqlSelect);
        query.getStatement().setFetchSize(getBufferSize());
        ResultSet resultSet = query.getResultSet();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        pw.print("Found ");
        pw.print(columnCount);
        pw.println(" column(s)");
        for (int i = 1; i <= columnCount; i++) {
            pw.print(i);
            pw.print(": ");
            pw.println(metaData.getColumnLabel(i));
        }
        return sw.toString();
    } finally {
        IOUtils.close(pw, sw);
        if (transaction != null)
            transaction.close();
    }
}

From source file:ro.nextreports.engine.util.QueryUtil.java

public List<NameType> executeQueryForColumnNames(String sql) throws Exception {
    // long t = System.currentTimeMillis();
    StringWriter sw = new StringWriter(100);
    // sw.append("SELECT * FROM (");
    sw.append(sql);//  w w w  . j  a  v  a 2 s .  c  o  m
    // sw.append(") A WHERE 1 = -1");

    String sqlForHeader = sw.toString();
    LOG.info("call for header columns = " + sqlForHeader);

    ResultSet rs = null;
    Statement stmt = null;
    try {
        if (isProcedureCall(sqlForHeader)) {
            Dialect dialect = DialectUtil.getDialect(con);
            CallableStatement cs = con.prepareCall("{" + sqlForHeader + "}");
            stmt = cs;
            if (dialect.hasProcedureWithCursor()) {
                cs.registerOutParameter(1, dialect.getCursorSqlType());
            }
            rs = cs.executeQuery();
            if (dialect.hasProcedureWithCursor()) {
                rs = (ResultSet) (cs.getObject(1));
            }
        } else {
            stmt = con.createStatement();
            stmt.setMaxRows(1);
            rs = stmt.executeQuery(sqlForHeader);
        }
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();

        List<NameType> columnNames = new ArrayList<NameType>();
        for (int i = 0; i < columnCount; i++) {
            columnNames.add(new NameType(rsmd.getColumnLabel(i + 1), dialect.getJavaType(
                    rsmd.getColumnTypeName(i + 1), rsmd.getPrecision(i + 1), rsmd.getScale(i + 1))));
            // rsmd.getColumnClassName(i + 1)));
        }

        // t = System.currentTimeMillis() - t;
        // System.out.println("execute query for column names in " + t +
        // "ms");

        return columnNames;
    } finally {
        ConnectionUtil.closeResultSet(rs);
        ConnectionUtil.closeStatement(stmt);
    }

}

From source file:org.atricore.idbus.idojos.dbidentitystore.IdentityDAO.java

/**
 * Builds an array of credentials based on a ResultSet
 * Column names are used to build a credential.
 *//*from  www . j  av a  2  s.c om*/
protected Credential[] fetchCredentials(ResultSet rs)
        throws SQLException, IOException, SSOAuthenticationException {

    if (rs.next()) {

        List creds = new ArrayList();
        ResultSetMetaData md = rs.getMetaData();

        // Each column is a credential, the column name is used as credential name ...
        for (int i = 1; i <= md.getColumnCount(); i++) {
            String cName = md.getColumnLabel(i);
            String cValue = rs.getString(i);
            Credential c = _cp.newCredential(cName, cValue);
            creds.add(c);
        }

        return (Credential[]) creds.toArray(new Credential[creds.size()]);
    }

    return new Credential[0];

}

From source file:org.apache.sqoop.connector.jdbc.GenericJdbcToInitializer.java

@Override
public Schema getSchema(InitializerContext context, LinkConfiguration linkConfig,
        ToJobConfiguration toJobConfig) {
    configureJdbcProperties(context.getContext(), linkConfig, toJobConfig);

    String schemaName = toJobConfig.toJobConfig.tableName;

    if (schemaName == null) {
        throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0019,
                "Table name extraction not supported yet.");
    }/*from   www  .ja  v a2s .c o m*/

    if (toJobConfig.toJobConfig.schemaName != null) {
        schemaName = toJobConfig.toJobConfig.schemaName + "." + schemaName;
    }

    Schema schema = new Schema(schemaName);
    ResultSet rs = null;
    ResultSetMetaData rsmt = null;
    try {
        rs = executor.executeQuery("SELECT * FROM " + schemaName + " WHERE 1 = 0");

        rsmt = rs.getMetaData();
        for (int i = 1; i <= rsmt.getColumnCount(); i++) {
            Column column = SqlTypesUtils.sqlTypeToAbstractType(rsmt.getColumnType(i));

            String columnName = rsmt.getColumnName(i);
            if (columnName == null || columnName.equals("")) {
                columnName = rsmt.getColumnLabel(i);
                if (null == columnName) {
                    columnName = "Column " + i;
                }
            }

            column.setName(columnName);
            schema.addColumn(column);
        }

        return schema;
    } catch (SQLException e) {
        throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0016, e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.info("Ignoring exception while closing ResultSet", e);
            }
        }
    }
}