List of usage examples for java.sql ResultSetMetaData getColumnName
String getColumnName(int column) throws SQLException;
From source file:eionet.cr.dao.virtuoso.VirtuosoStagingDatabaseDAO.java
@Override public Set<String> prepareStatement(String sql, String dbName) throws DAOException { if (StringUtils.isBlank(sql)) { throw new IllegalArgumentException("The given SQL statement must not be blank!"); }// w ww . jav a 2 s. c o m LinkedHashSet<String> result = new LinkedHashSet<String>(); Connection conn = null; PreparedStatement pstmt = null; try { conn = getSQLConnection(dbName); pstmt = SQLUtil.prepareStatement(sql, null, conn); ResultSetMetaData metaData = pstmt.getMetaData(); int colCount = metaData.getColumnCount(); for (int i = 1; i <= colCount; i++) { String colName = metaData.getColumnName(i); result.add(colName); } } catch (SQLException e) { throw new DAOException(e.getMessage(), e); } finally { SQLUtil.close(pstmt); SQLUtil.close(conn); } return result; }
From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java
private List<LogMessage> toLogMessageInternal(ResultSet rs, List<LogMessage> logMessages) { try {/*from w w w . j ava 2 s .com*/ // we will need the column names. java.sql.ResultSetMetaData rsmd = rs.getMetaData(); //loop through the ResultSet while (rs.next()) { //figure out how many columns there are int numColumns = rsmd.getColumnCount(); //each row in the ResultSet will be converted to a Object LogMessage obj = new LogMessage(); // loop through all the columns for (int i = 1; i < numColumns + 1; i++) { String column_name = rsmd.getColumnName(i); if (column_name.equals("ID")) { obj.setId(rs.getBigDecimal(column_name).longValueExact()); } if (column_name.equals("APPLICATIONNAME")) { obj.setApplicationName(rs.getNString(column_name)); } if (column_name.equals("EXPIREDDATE")) { obj.setExpiredDate(rs.getDate(column_name)); } if (column_name.equals("FLOWNAME")) { obj.setFlowName(rs.getNString(column_name)); } if (column_name.equals("FLOWPOINTNAME")) { obj.setFlowPointName(rs.getNString(column_name)); } if (column_name.equals("ISERROR")) { obj.setIsError(rs.getBoolean(column_name)); } if (column_name.equals("TRANSACTIONREFERENCEID")) { obj.setTransactionReferenceID(rs.getNString(column_name)); } if (column_name.equals("UTCLOCALTIMESTAMP")) { obj.setUtcLocalTimeStamp(rs.getTimestamp(column_name)); } if (column_name.equals("UTCSERVERTIMESTAMP")) { obj.setUtcServerTimeStamp(rs.getTimestamp(column_name)); } } //end foreach logMessages.add(obj); } //end while } catch (Exception e) { e.printStackTrace(); } return logMessages; }
From source file:ResultSetIterator.java
/** * Convert a <code>ResultSet</code> row into a <code>Map</code>. This * implementation returns a <code>Map</code> with case insensitive column * names as keys. Calls to <code>map.get("COL")</code> and * <code>map.get("col")</code> return the same value. * @see org.apache.commons.dbutils.RowProcessor#toMap(java.sql.ResultSet) *//*from w w w . j a v a 2 s .c om*/ public Map toMap(ResultSet rs) throws SQLException { Map result = new CaseInsensitiveHashMap(); ResultSetMetaData rsmd = rs.getMetaData(); int cols = rsmd.getColumnCount(); for (int i = 1; i <= cols; i++) { result.put(rsmd.getColumnName(i), rs.getObject(i)); } return result; }
From source file:com.ws.WS_TCS201.java
@Path("/GetDETAIL/{com}/{account}") @JSONP(queryParam = "callback") @GET//from ww w . j a v a 2s .co m @Produces({ "application/x-javascript" }) public String GetDETAIL(@QueryParam("callback") String callback, @PathParam("com") String com, @PathParam("account") String account) { JSONObject obj1 = new JSONObject(); LinkedList l1 = new LinkedList(); PreparedStatement prepStmt = null; try { // String cSQL = " SELECT tceemp, tceapd, tceall, tcetkb, tcetkt FROM TCSTCE " + " WHERE tcecom= ? AND tceemp= ? " + " ORDER BY tceapd DESC"; prepStmt = connection.prepareStatement(cSQL); prepStmt.setString(1, com); prepStmt.setString(2, account); ResultSet result = prepStmt.executeQuery(); if (result.next()) { LinkedHashMap m1 = new LinkedHashMap(); Object obj = result.getObject(2); //? m1.put("arrive", obj.toString().substring(0, 4) + "/" + obj.toString().substring(4, 6) + "/" + obj.toString().substring(6, 8)); // if (Integer.parseInt(obj.toString()) < 20100913) { m1.put("start", "01/01"); } else { m1.put("start", obj.toString().substring(4, 6) + "/" + obj.toString().substring(6, 8)); } // obj = result.getObject(3); m1.put("allday", obj.toString()); l1.add(m1); } obj1.put("base", l1); // result.close(); l1.clear(); cSQL = " SELECT tch.tchyer,CONCAT(tch.tchtcd,\" - \",tcc.tcctxt) AS tcdnam,tch.tchdst,tch.tchded,tch.tchday,tch.tchlst,tch.tchtxt,tch.tchtcd,tch.tchtck, " + " IFNULL(tchgrp.maxtck,\"\") AS maxtck, IFNULL(tchgrp.maxdst,0) AS maxdst " + " FROM TCSTCH AS tch " + " LEFT JOIN (SELECT DISTINCT tcecom,tceemp,tcenam FROM TCSTCE) AS tce " + " ON tcecom=tchcom AND tce.tceemp=tch.tchemp " + " LEFT JOIN (SELECT tcctcd, tcctxt FROM TCSTCC ) AS tcc " + " ON tcc.tcctcd=tch.tchtcd " + " LEFT JOIN ( SELECT tchcom,tchemp,tchyer,max(tchtck) AS maxtck,max(tchdst) AS maxdst FROM TCSTCH " + " WHERE tchtcd not in (\"B\",\"T\",\"M\",\"F\",\"W\") " + " GROUP BY tchcom,tchemp,tchyer ) AS tchgrp " + " ON tch.tchcom = tchgrp.tchcom AND tch.tchemp = tchgrp.tchemp " + " AND tch.tchyer = tchgrp.tchyer " + " WHERE tch.tchcom= ? AND tch.tchemp= ? " + " AND tcc.tcctcd NOT IN (\"A\",\"L\",\"R\",\"J\",\"N\") " + " AND tch.tchmrk=\" \" AND tch.tchyer >= 2014 " + " ORDER BY tch.tchemp,tch.tchdst DESC "; //" tchmrk=\" \" AND tchyer >= CONV( SUBSTR(NOW( ),1,4),10,10) -1 " + prepStmt = connection.prepareStatement(cSQL); prepStmt.setString(1, com); prepStmt.setString(2, account); result = prepStmt.executeQuery(); ResultSetMetaData rsmd = result.getMetaData(); int numcols = rsmd.getColumnCount(); while (result.next()) { LinkedHashMap m1 = new LinkedHashMap(); for (int j = 1; j <= numcols; j++) { Object obj = result.getObject(j); m1.put(rsmd.getColumnName(j).toString(), obj.toString()); } Object obj = result.getObject("tchtcd"); String chk1 = obj.toString(); obj = result.getObject("tchtck"); String chk2 = obj.toString(); obj = result.getObject("tchdst"); String chk3 = obj.toString(); obj = result.getObject("maxdst"); String chk4 = obj.toString(); if (((chk1.equals("M") || chk1.equals("F") || chk1.equals("W") || chk1.equals("B") || chk1.equals("T")) && chk2.equals("-")) || (!chk1.equals("M") && !chk1.equals("F") && !chk1.equals("W") && !chk1.equals("B") && !chk1.equals("T") && chk3.equals(chk4))) { m1.put("edit", "Y"); } else { m1.put("edit", "N"); } l1.add(m1); } obj1.put("detail", l1); } catch (SQLException e) { prepStmt = null; e.printStackTrace(); } catch (Exception e) { prepStmt = null; e.printStackTrace(); } return obj1.toString(); }
From source file:kenh.xscript.database.beans.ResultSetBean.java
/** * Use result set to initial a bean.//w w w . java2s . c o m * * @param rs * @param includeFieldName * @throws SQLException * @throws IllegalAccessException * @throws InstantiationException */ public ResultSetBean(ResultSet rs, boolean includeFieldName) throws SQLException, IllegalAccessException, InstantiationException { include_field_name = includeFieldName; LazyDynaClass beanClass = new LazyDynaClass(); ResultSetMetaData m = rs.getMetaData(); for (int i = 1; i <= m.getColumnCount(); i++) { Column c = new Column(); try { c.catalogName = m.getCatalogName(i); } catch (SQLException e) { } try { c.className = m.getColumnClassName(i); } catch (SQLException e) { } try { c.displaySize = m.getColumnDisplaySize(i); } catch (SQLException e) { } try { c.label = m.getColumnLabel(i); } catch (SQLException e) { } try { c.name = m.getColumnName(i); } catch (SQLException e) { } try { c.type = m.getColumnType(i); } catch (SQLException e) { } try { c.typeName = m.getColumnTypeName(i); } catch (SQLException e) { } try { c.precision = m.getPrecision(i); } catch (SQLException e) { } try { c.scale = m.getScale(i); } catch (SQLException e) { } try { c.schemaName = m.getSchemaName(i); } catch (SQLException e) { } try { c.tableName = m.getTableName(i); } catch (SQLException e) { } beanClass.add(m.getColumnLabel(i).toLowerCase()); beanClass.add("" + i); cols.add(c); } DynaBean colBean = beanClass.newInstance(); int i = 1; for (Column col : cols) { String field = col.getLabel().toLowerCase(); colBean.set(field, col.getLabel()); colBean.set("" + i, col.getLabel()); i++; } if (include_field_name) rows.add(colBean); while (rs.next()) { DynaBean bean = beanClass.newInstance(); i = 1; for (Column c : cols) { String field = c.getLabel().toLowerCase(); Object obj = rs.getObject(field); bean.set(field, obj); bean.set("" + i, obj); i++; } rows.add(bean); } }
From source file:org.ensembl.healthcheck.util.DBUtils.java
/** * Scans through a result set's metadata in an attempt to find a column * // w w w .ja va2 s . c o m * @param rs * The ResultSet to scan * @param column * The column to find * @return Boolean indicating if there was a column with said name * @throws SQLException * Thrown in the event of an error whilst processing */ public static boolean resultSetContainsColumn(ResultSet rs, String column) throws SQLException { ResultSetMetaData meta = rs.getMetaData(); int total = meta.getColumnCount(); for (int i = 1; i <= total; i++) { if (meta.getColumnName(i).equals(column)) { return true; } } return false; }
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 {// w w w . jav a2 s . c o m 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.kylin.query.KylinTestBase.java
protected int output(ResultSet resultSet, boolean needDisplay) throws SQLException { int count = 0; ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); StringBuilder sb = new StringBuilder("\n"); if (needDisplay) { for (int i = 1; i <= columnCount; i++) { sb.append(metaData.getColumnName(i)); sb.append("-"); sb.append(metaData.getTableName(i)); sb.append("-"); sb.append(metaData.getColumnTypeName(i)); if (i < columnCount) { sb.append("\t"); } else { sb.append("\n"); }//from www . j av a2 s. c o m } } while (resultSet.next()) { if (needDisplay) { for (int i = 1; i <= columnCount; i++) { sb.append(resultSet.getString(i)); if (i < columnCount) { sb.append("\t"); } else { sb.append("\n"); } } } count++; } logger.info(sb.toString()); return count; }
From source file:com.cloudera.sqoop.manager.SqlManager.java
/** * Get column types for a query statement that we do not modify further. *//*w w w . ja va 2 s . c om*/ protected Map<String, Integer> getColumnTypesForRawQuery(String stmt) { ResultSet results; try { results = execute(stmt); } catch (SQLException sqlE) { LOG.error("Error executing statement: " + sqlE.toString()); release(); return null; } 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; } finally { try { results.close(); getConnection().commit(); } catch (SQLException sqlE) { LOG.warn("SQLException closing ResultSet: " + sqlE.toString()); } release(); } }
From source file:com.yahoo.dba.perf.myperf.springmvc.UdmController.java
/** * /*from w w w. j a v a 2 s . c o m*/ * Test UDM, use exception to send out message * @param req * @param udm * @param db * @throws SQLException */ private void testUDM(HttpServletRequest req, UserDefinedMetrics udm, String db) throws Exception { if (db == null || db.isEmpty()) throw new Exception("please provide valid database for test"); String[] dbs = db.split("\\|"); if (dbs == null || dbs.length < 2) throw new Exception("please provide valid database for test"); DBInstanceInfo dbinfo = this.frameworkContext.getDbInfoManager().findDB(dbs[0], dbs[1]); if (dbinfo == null) throw new Exception("please provide valid database for test"); HashSet<String> metricsNameSet = new HashSet<String>(); for (Metric m : udm.getMetrics()) { metricsNameSet.add(m.getSourceName()); } DBConnectionWrapper connWrapper = null; Statement stmt = null; ResultSet rs = null; try { String sql = udm.getSql(); MetricsGroup mg = udm.getMetricsGroup(); String udmType = udm.getUdmType(); String nameCol = udm.getNameCol(); String valCol = udm.getValueCol(); String keyCol = udm.getKeyCol(); boolean isBuiltin = false; if (!"SQL".equals(udm.getSource())) { sql = this.frameworkContext.getSqlTextForMetricsGroup(udm.getSource()); mg = this.frameworkContext.getMetricsDef().getGroupByName(udm.getSource()); if (mg != null) { if (mg.getKeyColumn() != null) udmType = "key"; else if (mg.isMultipleMetricsPerRow()) udmType = "column"; else udmType = "row"; nameCol = mg.getMetricNameColumn(); valCol = mg.getMetricValueColumn(); keyCol = mg.getKeyColumn(); } isBuiltin = true; } if (sql == null || sql.isEmpty()) { throw new Exception("please provide valid SQL"); } connWrapper = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo); if (connWrapper == null) { throw new Exception("failed to connect to target db (" + dbinfo + ")"); } stmt = connWrapper.getConnection().createStatement(); rs = stmt.executeQuery(sql); if (rs != null) { ResultSetMetaData meta = rs.getMetaData(); //verify columns int cols = meta.getColumnCount(); Map<String, Integer> colMap = new HashMap<String, Integer>(cols); for (int i = 1; i <= cols; i++) colMap.put(meta.getColumnName(i).toUpperCase(), meta.getColumnType(i)); if ("row".equals(udmType)) { if (!colMap.containsKey(udm.getNameCol().toUpperCase())) throw new Exception("Failed to find name column from SQL result: " + udm.getNameCol() + ", returned: " + colMap); if (!colMap.containsKey(udm.getValueCol().toUpperCase())) throw new Exception("Failed to find value column from SQL result: " + udm.getValueCol() + ", returned: " + colMap); } else //check metrics column { if ("key".equals(udmType)) { if (!colMap.containsKey(keyCol.toUpperCase())) throw new Exception("Failed to find key column from SQL result: " + udm.getKeyCol()); } for (Metric m : udm.getMetrics()) { if (!colMap.containsKey(m.getSourceName().toUpperCase())) throw new Exception( "Failed to find metric column from SQL result: " + m.getSourceName()); } } } else { throw new Exception("Failed to test SQL."); } while (rs != null && rs.next()) { if ("row".equals(udmType)) { String name = rs.getString(nameCol); if (!metricsNameSet.contains(name)) continue; String val = rs.getString(valCol); try { BigDecimal d = new BigDecimal(val == null ? "0" : val); } catch (Exception ex) { throw new Exception("Expect numeric value for metric from SQL result, got " + val); } } else { for (Metric m : udm.getMetrics()) { String val = rs.getString(m.getSourceName()); try { BigDecimal d = new BigDecimal(val == null ? "0" : val); } catch (Exception ex) { throw new Exception("Expect numeric value metric value from SQL result for column " + m.getShortName() + ", got " + val); } } } } } finally { DBUtils.close(rs); DBUtils.close(stmt); WebAppUtil.closeDBConnection(req, connWrapper, true);//close it anyway } }