List of usage examples for java.sql ResultSetMetaData getColumnCount
int getColumnCount() throws SQLException;
ResultSet
object. From source file:io.github.huherto.springyRecords.RecordMapper.java
/** * Extract the values for all columns in the current row. * <p>Utilizes public setters and result set metadata. * @see java.sql.ResultSetMetaData/* w w w .j a va2s . c o m*/ */ @Override public T mapRow(ResultSet rs, int rowNumber) throws SQLException { Assert.state(this.mappedClass != null, "Mapped class was not specified"); T mappedObject; try { mappedObject = mappedClass.newInstance(); } catch (Exception ex) { throw new RuntimeException(ex); } ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int index = 1; index <= columnCount; index++) { String column = JdbcUtils.lookupColumnName(rsmd, index); Field field = this.mappedFields.get(column.replaceAll(" ", "")); if (field != null) { Object value = getColumnValue(rs, index, field); if (logger.isTraceEnabled() && rowNumber == 0) { logger.trace("Mapping column '" + column + "' to property '" + field.getName() + "' of type " + field.getType()); } try { field.set(mappedObject, value); } catch (IllegalArgumentException e) { if (value == null && primitivesDefaultedForNullValue) { logger.debug("Intercepted IllegalArgumentException for row " + rowNumber + " and column '" + column + "' with value " + value + " when setting property '" + field.getName() + "' of type " + field.getType() + " on object: " + mappedObject); } else { throw e; } } catch (IllegalAccessException e) { e.printStackTrace(); } } } return mappedObject; }
From source file:de.tudarmstadt.ukp.dkpro.core.io.jdbc.JdbcReader.java
private void query() throws ResourceInitializationException { try {/*from w w w . j a va 2 s . co m*/ Statement statement = sqlConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); resultSet = statement.executeQuery(query); resultSet.last(); resultSetSize = resultSet.getRow(); resultSet.beforeFirst(); completed = 0; // Store available column names columnNames = new HashSet<String>(); ResultSetMetaData meta = resultSet.getMetaData(); for (int i = 1; i < meta.getColumnCount() + 1; i++) { String columnName = meta.getColumnLabel(i); columnNames.add(columnName); if (!CAS_COLUMNS.contains(columnName)) { getLogger().warn("Unknown column [" + columnName + "]."); } } } catch (SQLException e) { throw new ResourceInitializationException(e); } }
From source file:db.migration.V055__UpdateECTS.java
public void migrate(JdbcTemplate jdbcTemplate) throws Exception { LOG.info("migrate()..."); // Get all organisaatiometadatas where there are strings to process List<Map> resultSet = jdbcTemplate.query( "SELECT id,hakutoimistoectsemail,hakutoimistoectsnimi,hakutoimistoectspuhelin,hakutoimistoectstehtavanimike FROM organisaatiometadata WHERE hakutoimistoectsemail<>'' OR hakutoimistoectsnimi<>'' OR hakutoimistoectspuhelin<>'' OR hakutoimistoectstehtavanimike<>''", new RowMapper<Map>() { @Override/*from ww w.j ava2 s . co m*/ public Map mapRow(ResultSet rs, int rowNum) throws SQLException { Map r = new HashMap<String, Object>(); ResultSetMetaData metadata = rs.getMetaData(); for (int i = 1; i <= metadata.getColumnCount(); i++) { String cname = metadata.getColumnName(i); int ctype = metadata.getColumnType(i); switch (ctype) { case Types.VARCHAR: // hakutoimistoectsemail,hakutoimistoectsnimi,hakutoimistoectspuhelin,hakutoimistoectstehtavanimike r.put(cname, rs.getString(cname)); break; case Types.BIGINT: // id r.put(cname, rs.getInt(cname)); break; default: break; } } LOG.debug(" read from db : organisaatiometadata = {}", r); return r; } }); // Move strings to monikielinenteksti_values for (Map orgmd : resultSet) { handleOrganisaatiometadata(orgmd, jdbcTemplate); } LOG.info("migrate()... done."); }
From source file:com.ibm.research.rdf.store.jena.impl.DB2ResultSetImpl.java
public DB2ResultSetImpl(LiteralInfoResultSet rs, Store store, Connection c, List<String> list, VarExprList varExprList) {/*from w ww.j av a2 s . c o m*/ liRs = rs; set = rs.getResultSet(); try { ResultSetMetaData rsMetaData = set.getMetaData(); int numberOfColumns = rsMetaData.getColumnCount(); // get the column names; column indexes start from 1 for (int i = 1; i <= numberOfColumns; i++) { columnNames.add(rsMetaData.getColumnName(i)); } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException("Error getting result metadata"); } this.store = store; connection = c; if (varExprList.isEmpty()) { varList = list; } else { List<Var> vars = varExprList.getVars(); varList = new ArrayList<String>(); for (int i = 0; i < vars.size(); i++) { varList.add(vars.get(i).getName()); } } }
From source file:bs.global.util.ExcelFactory.java
public void generate(OutputStream outputStream) throws Exception { try {/*from w w w.ja va 2 s . c om*/ ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); if (formatTypes != null && formatTypes.length != resultSetMetaData.getColumnCount()) { throw new IllegalStateException("Number of types is not identical to number of resultset columns. " + "Number of types: " + formatTypes.length + ". Number of columns: " + resultSetMetaData.getColumnCount()); } int currentRow = 0; HSSFRow row = sheet.createRow(currentRow); int numCols = resultSetMetaData.getColumnCount(); boolean isAutoDecideFormatTypes; if (isAutoDecideFormatTypes = (formatTypes == null)) { formatTypes = new FormatType[numCols]; } for (int i = 0; i < numCols; i++) { String title = resultSetMetaData.getColumnName(i + 1); writeCell(row, i, title, FormatType.TEXT, boldFont); if (isAutoDecideFormatTypes) { Class _class = Class.forName(resultSetMetaData.getColumnClassName(i + 1)); formatTypes[i] = getFormatType(_class); } } currentRow++; // Write report rows while (resultSet.next()) { row = sheet.createRow(currentRow++); for (int i = 0; i < numCols; i++) { Object value = resultSet.getObject(i + 1); writeCell(row, i, value, formatTypes[i]); } } // Autosize columns for (int i = 0; i < numCols; i++) { sheet.autoSizeColumn((short) i); } workbook.write(outputStream); } finally { outputStream.close(); } }
From source file:org.owasp.webgoat.plugin.CrossSiteScriptingLesson5b.java
public String writeTable(ResultSet results, ResultSetMetaData resultsMetaData) throws IOException, SQLException { int numColumns = resultsMetaData.getColumnCount(); results.beforeFirst();/*from w w w. j ava2s . co m*/ StringBuffer t = new StringBuffer(); t.append("<p>"); if (results.next()) { for (int i = 1; i < (numColumns + 1); i++) { t.append(resultsMetaData.getColumnName(i)); t.append(", "); } t.append("<br />"); results.beforeFirst(); while (results.next()) { for (int i = 1; i < (numColumns + 1); i++) { t.append(results.getString(i)); t.append(", "); } t.append("<br />"); } } else { t.append("Query Successful; however no data was returned from this query."); } t.append("</p>"); return (t.toString()); }
From source file:com.svds.resttest.services.GenericDataService.java
/** * Obtain metaDataSet from rs and add to genericResultsOutput * /*from w w w .j ava 2s .c o m*/ * @param rs result set containing metadata * @param metaDataSet metadata map to add to * @param genericResultsOutput output object to add metadata to * @throws SQLException */ private void getMetaData(ResultSet rs, Map<String, Integer> metaDataSet, GenericResultsOutput genericResultsOutput) throws SQLException { LOG.info(">>>>Starting getMetaData"); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); List<MetaData> metaDataArrayList = genericResultsOutput.getMetaData(); for (int i = 1; i <= columnCount; i++) { metaDataSet.put(rsmd.getColumnName(i), Integer.valueOf(i)); Map<String, Object> columnAttributes = new HashMap<>(); columnAttributes.put("ColumnTypeName", rsmd.getColumnTypeName(i)); columnAttributes.put("IndexNumber", i); MetaData metaData = new MetaData(); metaData.setColumnName(rsmd.getColumnName(i)); metaData.setColumnAttributes(columnAttributes); LOG.info("getColumnType : " + rsmd.getColumnType(i)); LOG.info("getColumnTypeName : " + rsmd.getColumnTypeName(i)); LOG.info("index : " + i); metaDataArrayList.add(metaData); } LOG.info(">>>>Ending getMetaData"); }
From source file:com.flexive.core.search.genericSQL.GenericSQLForeignTableSelector.java
protected GenericSQLForeignTableSelector(String mainColumn, String tableName, String linksOn, boolean hasTranslationTable, String translatedColumn) { FxSharedUtils.checkParameterNull(tableName, "tableName"); FxSharedUtils.checkParameterNull(linksOn, "linksOn"); Connection con = null;//ww w . ja v a 2 s .co m Statement stmt = null; this.tableName = tableName; this.linksOn = linksOn; this.mainColumn = mainColumn; this.hasTranslationTable = hasTranslationTable; this.translatedColumn = translatedColumn != null ? translatedColumn.toUpperCase() : null; try { con = Database.getDbConnection(); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName + StorageManager.getLimit(false, 0)); ResultSetMetaData md = rs.getMetaData(); for (int pos = 1; pos <= md.getColumnCount(); pos++) { String columnName = md.getColumnName(pos); FxDataType columnType; switch (md.getColumnType(pos)) { case java.sql.Types.CHAR: if (md.getPrecision(pos) == 1) { columnType = FxDataType.Boolean; //oracle break; } case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: case java.sql.Types.CLOB: columnType = FxDataType.String1024; break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: columnType = FxDataType.Boolean; break; case java.sql.Types.TINYINT: case java.sql.Types.SMALLINT: case java.sql.Types.INTEGER: columnType = FxDataType.Number; break; case java.sql.Types.DECIMAL: columnType = FxDataType.Double; break; case java.sql.Types.FLOAT: columnType = FxDataType.Float; break; case java.sql.Types.NUMERIC: case java.sql.Types.BIGINT: if ("CREATED_AT".equalsIgnoreCase(columnName) || "MODIFIED_AT".equalsIgnoreCase(columnName)) columnType = FxDataType.DateTime; else if ("CAT_TYPE".equals(columnName) && "FXS_ACL".equals(tableName)) { columnType = FxDataType.Number; } else columnType = FxDataType.LargeNumber; break; case java.sql.Types.DATE: columnType = FxDataType.Date; break; case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: columnType = FxDataType.DateTime; break; default: if (LOG.isInfoEnabled()) { LOG.info("Assigning String to " + tableName + "." + columnName + " found type=" + md.getColumnType(pos)); } columnType = FxDataType.String1024; } columns.put(columnName.toUpperCase(), columnType); } } catch (Throwable t) { @SuppressWarnings({ "ThrowableInstanceNeverThrown" }) FxSqlSearchException ex = new FxSqlSearchException(LOG, "ex.sqlSearch.fieldSelector.initializeFailed", tableName, t.getMessage()); LOG.error(ex.getMessage(), ex); throw ex.asRuntimeException(); } finally { Database.closeObjects(GenericSQLForeignTableSelector.class, con, stmt); } }
From source file:com.kumarvv.setl.utils.RowSetUtil.java
/** * get meta columns list with columnId/* ww w. j a v a 2 s. c o m*/ * * @param meta * @return */ public Map<String, Integer> getMetaColumns(ResultSetMetaData meta) { final Map<String, Integer> metaColumns = new HashMap<>(); if (meta == null) { return metaColumns; } try { int colCount = meta.getColumnCount(); for (int c = 1; c <= colCount; c++) { metaColumns.put(meta.getColumnName(c), meta.getColumnType(c)); } } catch (SQLException sqle) { Logger.error("error getting metaColumns:", sqle.getMessage()); Logger.trace(sqle); } return metaColumns; }
From source file:com.streamsets.pipeline.stage.executor.jdbc.TestJdbcQueryExecutor.java
/** * Validate structure of the result set (column names and types). *//*from w w w .j a v a 2 s.c o m*/ public void assertResultSetStructure(ResultSet rs, Pair<String, Integer>... columns) throws Exception { ResultSetMetaData metaData = rs.getMetaData(); Assert.assertEquals(Utils.format("Unexpected number of columns"), columns.length, metaData.getColumnCount()); int i = 1; for (Pair<String, Integer> column : columns) { Assert.assertEquals(Utils.format("Unexpected name for column {}", i), column.getLeft(), metaData.getColumnName(i)); Assert.assertEquals(Utils.format("Unexpected type for column {}", i), (int) column.getRight(), metaData.getColumnType(i)); i++; } }