List of usage examples for java.sql ResultSet getObject
Object getObject(String columnLabel) throws SQLException;
Gets the value of the designated column in the current row of this ResultSet
object as an Object
in the Java programming language.
From source file:org.h2gis.drivers.geojson.GeoJsonWriteDriver.java
/** * Write the GeoJSON properties./*from ww w .j av a 2 s.c om*/ * * @param jsonGenerator * @param rs * @throws IOException */ private void writeProperties(JsonGenerator jsonGenerator, ResultSet rs) throws IOException, SQLException { if (columnCountProperties != -1) { jsonGenerator.writeObjectFieldStart("properties"); for (Map.Entry<String, Integer> entry : cachedColumnNames.entrySet()) { String string = entry.getKey(); Integer fieldId = entry.getValue(); jsonGenerator.writeObjectField(string, rs.getObject(fieldId)); } jsonGenerator.writeEndObject(); } }
From source file:com.nextep.datadesigner.sqlgen.impl.generator.DataSetGenerator.java
private ISQLScript buildScript(IDataSet set, IDataSet valuesSet, DeltaType type) { final ISQLScript script = CorePlugin.getTypedObjectFactory().create(ISQLScript.class); script.setScriptType(ScriptType.DATA); script.setName(type.name().toLowerCase() + "." + set.getName()); //$NON-NLS-1$ final StringBuilder buf = new StringBuilder(2000); final ISQLParser parser = SQLGenPlugin.getService(IGenerationService.class).getCurrentSQLParser(); // final IDataService dataService = DbgmPlugin.getService(IDataService.class); final IStorageService storageService = DbgmPlugin.getService(IStorageService.class); final IStorageHandle handle = valuesSet.getStorageHandle(); if (handle != null) { Connection conn = null;//from ww w . j ava2 s.c o m Statement stmt = null; ResultSet rset = null; try { conn = storageService.getLocalConnection(); stmt = conn.createStatement(); stmt.execute(handle.getSelectStatement()); rset = stmt.getResultSet(); final ResultSetMetaData md = rset.getMetaData(); while (rset.next()) { final List<Object> values = new LinkedList<Object>(); for (int i = 1; i <= md.getColumnCount(); i++) { values.add(rset.getObject(i)); } switch (type) { case INSERT: buf.append(buildInsert(parser, set, values)); break; case UPDATE: buf.append(buildUpdate(parser, set, values)); break; case DELETE: buf.append(buildDelete(parser, set, values)); break; } } } catch (SQLException e) { throw new ErrorException("Data generation problem: " + e.getMessage(), e); } finally { safeClose(rset, stmt, conn); } } if (buf.length() == 0) { return null; } else { script.appendSQL(buf.toString()); return script; } }
From source file:com.serphacker.serposcope.db.base.ExportDB.java
public boolean export(Writer writer) throws IOException { for (String resource : MigrationDB.DB_SCHEMA_FILES) { String sql = new String(ByteStreams.toByteArray(MigrationDB.class.getResourceAsStream(resource))); sql = sql.replaceAll("--.*\n", "\n"); sql = sql.replaceAll("\\s+", " "); sql = sql.replaceAll(";\\s*", ";\n"); writer.append(sql);/*www .j a v a2s . co m*/ writer.append("\n"); } writer.append("\nSET FOREIGN_KEY_CHECKS=0;\n"); try (Connection con = ds.getConnection()) { for (String table : TABLES) { writer.flush(); try (Statement stmt = con.createStatement()) { LOG.info("exporting table {}", table); long _start = System.currentTimeMillis(); stmt.setQueryTimeout(3600 * 24); ResultSet rs = stmt.executeQuery("SELECT * FROM `" + table + "`"); ResultSetMetaData metaData = rs.getMetaData(); int columns = metaData.getColumnCount(); String insertStatement = "INSERT INTO `" + table + "` VALUES "; StringBuilder stmtBuilder = new StringBuilder(insertStatement); while (rs.next()) { StringBuilder entryBuilder = new StringBuilder("("); for (int colIndex = 1; colIndex <= columns; colIndex++) { Object object = rs.getObject(colIndex); String colName = metaData.getColumnName(colIndex); String colClassName = metaData.getColumnClassName(colIndex); String escaped = escape(object, colClassName, colName); entryBuilder.append(escaped); if (colIndex < columns) { entryBuilder.append(','); } } entryBuilder.append("),"); if (stmtBuilder.length() != insertStatement.length() && stmtBuilder.length() + entryBuilder.length() > DEFAULT_MAX_ALLOWED_PACKET) { stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';'); writer.append(stmtBuilder).append('\n'); stmtBuilder = new StringBuilder(insertStatement); } stmtBuilder.append(entryBuilder); } if (stmtBuilder.length() != insertStatement.length()) { stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';'); writer.append(stmtBuilder).append('\n'); } LOG.info("exported table {} in {}", table, DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start)); } } writer.append("SET FOREIGN_KEY_CHECKS=1;\n"); } catch (Exception ex) { LOG.error("SQL error", ex); return false; } return true; }
From source file:com.termmed.statistics.Processor.java
/** * Prints the report.//from ww w. j ava2 s. c o m * * @param bw the bw * @param tableMap the table map * @throws Exception the exception */ private void printReport(BufferedWriter bw, OutputFileTableMap tableMap) throws Exception { SQLStatementExecutor executor = new SQLStatementExecutor(connection); for (SelectTableMap select : tableMap.getSelect()) { String query = "Select * from " + select.getTableName(); if (executor.executeQuery(query, null)) { ResultSet rs = executor.getResultSet(); if (rs != null) { ResultSetMetaData meta = rs.getMetaData(); while (rs.next()) { for (int i = 0; i < meta.getColumnCount(); i++) { if (rs.getObject(i + 1) != null) { bw.append(rs.getObject(i + 1).toString()); } else { bw.append(""); } if (i + 1 < meta.getColumnCount()) { bw.append(","); } else { bw.append("\r\n"); } } } meta = null; rs.close(); } } } executor = null; }
From source file:esavo.tap.formatter.ResultSet2JsonFormatter.java
@Override protected int writeData(UwsJob job, ResultSet queryResult, DBColumn[] selectedColumns, JSONWriter out, TAPExecutionReport execReport) throws IOException, TAPException, InterruptedException, JSONException { out.array();/*from w ww . j a v a 2 s . com*/ int nbRows = 0; try { int nbColumns = queryResult.getMetaData().getColumnCount(); while (queryResult.next()) { if (job.isPhaseAborted()) { break; } if (execReport.parameters.getMaxRec() > 0 && nbRows >= execReport.parameters.getMaxRec()) // that's to say: OVERFLOW ! break; out.array(); Object value; for (int i = 1; i <= nbColumns; i++) { value = formatValue(queryResult.getObject(i), selectedColumns[i - 1]); writeFieldValue(value, selectedColumns[i - 1], out); // if (thread.isInterrupted()) // throw new InterruptedException(); } out.endArray(); nbRows++; // if (thread.isInterrupted()) // throw new InterruptedException(); } } catch (SQLException se) { throw new TAPException("Job N" + execReport.jobID + " - Impossible to get the " + (nbRows + 1) + "-th rows from the given ResultSet !", se); } out.endArray(); return nbRows; }
From source file:com.netspective.axiom.sql.ResultSetUtils.java
public Map[] getResultSetRowsAsMapArray(ResultSet rs, boolean useLabelAsKey) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); int colsCount = rsmd.getColumnCount(); String[] columnNames = new String[colsCount]; for (int c = 1; c <= colsCount; c++) { columnNames[c - 1] = useLabelAsKey ? rsmd.getColumnLabel(c).toLowerCase() : rsmd.getColumnName(c).toLowerCase(); }//from w w w .j av a 2 s . c o m ArrayList result = new ArrayList(); while (rs.next()) { Map rsMap = new HashMap(); for (int i = 1; i <= colsCount; i++) { rsMap.put(columnNames[i - 1], rs.getObject(i)); } result.add(rsMap); } if (result.size() > 0) return (Map[]) result.toArray(new Map[result.size()]); else return null; }
From source file:ips1ap101.lib.core.control.Controlador.java
/** * Getter para propiedad referenciaAutorizada. * * @param recurso Identificacion del recurso. * @param funcion Identificacion de la funcion. * @param strings Vector de nombres: [0] Tabla, [1] Columna Identificacion, [2] Columna Propietario, [3] Columna Segmento. * @return true, si el usuario ejecutante esta autorizado para ejecutar la funcion sobre el recurso o si el recurso es nulo. *//*from ww w. ja v a2s .c o m*/ public boolean esReferenciaAutorizada(Object recurso, long funcion, String[] strings) { if (recurso == null || this.esSuperUsuario()) { return true; } String comando = this.getComandoSelectReferencia(recurso, funcion, strings); Bitacora.trace("comando" + "=" + comando); if (comando == null) { return false; } boolean es = false; String sql1 = comando; Object resultado1; ResultSet resultSet1 = null; Object objeto1; if (TLC.getAgenteSql().connected()) { try { resultado1 = TLC.getAgenteSql().executeQuery(sql1); if (resultado1 instanceof ResultSet) { resultSet1 = (ResultSet) resultado1; if (resultSet1.next()) { objeto1 = resultSet1.getObject(1); if (objeto1 != null) { es = true; } else { /* TODO: error handling */ } } else { /* TODO: error handling */ } } else { /* TODO: error handling */ } } catch (SQLException e) { TLC.getBitacora().fatal(e); } finally { DB.close(resultSet1); } } else { /* TODO: error handling */ } return es; }
From source file:com.ewcms.plugin.report.generate.factory.ChartFactory.java
/** * ?//from ww w .j ava 2s . c om * * @param reportDataSet ?? * @param sql SQL? * @return DefaultCategoryDataset * @throws BaseException */ @SuppressWarnings("rawtypes") private DefaultCategoryDataset buildDataset(ChartReport report, Map<String, String> pageParams) throws BaseException { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Connection con = null; EwcmsDataSourceServiceable service = null; int colCount; try { BaseDS dataSet = report.getBaseDS(); String executableSQL = report.getChartSql(); executableSQL = replaceParam(pageParams, report.getParameters(), executableSQL, true); if (dataSet == null) { con = dataSource.getConnection(); } else { DataSourceFactoryable factory = (DataSourceFactoryable) getAlqcDataSourceFactory() .getBean(dataSet.getClass()); service = factory.createService(dataSet); con = service.openConnection(); } Statement st = con.createStatement(); ResultSet rs = st.executeQuery(executableSQL); colCount = rs.getMetaData().getColumnCount(); if (colCount == 2) { while (rs.next()) { try { try { dataset.addValue(rs.getDouble(1), "", (Comparable) rs.getObject(2)); } catch (Exception e) { dataset.addValue(rs.getDouble(2), "", (Comparable) rs.getObject(1)); } // if (rs.getMetaData().getColumnType(1) == Types.NUMERIC){ // dataset.addValue(rs.getDouble(1), "", (Comparable) rs.getObject(2)); // }else if (rs.getMetaData().getColumnType(2) == Types.NUMERIC) { // dataset.addValue(rs.getDouble(2), "", (Comparable) rs.getObject(1)); // } } catch (Exception e) { logger.error("SQL?", e); throw new BaseException("SQL?", "SQL?"); } } } else if (colCount == 3) { while (rs.next()) { try { // log.info(rs.getMetaData().getColumnType(1)); // log.info(rs.getMetaData().getColumnType(2)); // log.info(rs.getMetaData().getColumnType(3)); // if (rs.getMetaData().getColumnType(1) == Types.NUMERIC){ // dataset.addValue(rs.getDouble(1), (Comparable) rs.getObject(2), (Comparable) rs.getObject(3)); // }else if (rs.getMetaData().getColumnType(2) == Types.NUMERIC){ // dataset.addValue(rs.getDouble(2), (Comparable) rs.getObject(1), (Comparable) rs.getObject(3)); // }else if (rs.getMetaData().getColumnType(3) == Types.NUMERIC){ // dataset.addValue(rs.getDouble(3), (Comparable) rs.getObject(1), (Comparable) rs.getObject(2)); // } try { dataset.addValue(rs.getDouble(3), (Comparable) rs.getObject(1), (Comparable) rs.getObject(2)); } catch (Exception e) { try { dataset.addValue(rs.getDouble(2), (Comparable) rs.getObject(1), (Comparable) rs.getObject(3)); } catch (Exception ex) { dataset.addValue(rs.getDouble(1), (Comparable) rs.getObject(2), (Comparable) rs.getObject(3)); } } } catch (Exception e) { logger.error("SQL?", e); throw new BaseException("SQL?", "SQL?"); } } } else { logger.error("SQL??12"); throw new BaseException("?12", "?12"); } st.close(); rs.close(); } catch (SQLException e) { throw new BaseException(e.toString(), e.toString()); } catch (ConvertException e) { throw new BaseException(e.toString(), e.toString()); } catch (ClassNotFoundException e) { throw new BaseException(e.toString(), e.toString()); } finally { if (service != null) { service.closeConnection(); } if (con != null) { try { con.close(); } catch (SQLException e) { } con = null; } } return dataset; }
From source file:com.datatorrent.contrib.enrichment.JDBCLoader.java
protected ArrayList<Object> getDataFrmResult(Object result) throws RuntimeException { try {// ww w.j av a 2s . c o m ResultSet resultSet = (ResultSet) result; if (resultSet.next()) { ResultSetMetaData rsdata = resultSet.getMetaData(); // If the includefields is empty, populate it from ResultSetMetaData if (CollectionUtils.isEmpty(includeFields)) { if (includeFields == null) { includeFields = new ArrayList<String>(); } for (int i = 1; i <= rsdata.getColumnCount(); i++) { includeFields.add(rsdata.getColumnName(i)); } } ArrayList<Object> res = new ArrayList<Object>(); for (String f : includeFields) { res.add(resultSet.getObject(f)); } return res; } else { return null; } } catch (SQLException e) { throw new RuntimeException(e); } }
From source file:com.squid.kraken.v4.caching.redis.datastruct.RawMatrix.java
public static RawMatrix readExecutionItem(IExecutionItem item, long maxRecords) throws SQLException, ScopeException { long metter_start = System.currentTimeMillis(); try {//from www . j a v a2 s . c om RawMatrix matrix = new RawMatrix(); ResultSet result = item.getResultSet(); IJDBCDataFormatter formatter = item.getDataFormatter(); // ResultSetMetaData metadata = result.getMetaData(); int nbColumns = metadata.getColumnCount(); IVendorSupport vendorSpecific; vendorSpecific = VendorSupportRegistry.INSTANCE.getVendorSupport(item.getDatabase()); int[] normalizedTypes = vendorSpecific.getVendorMetadataSupport().normalizeColumnType(result); int i = 0; while (i < nbColumns) { matrix.colTypes.add(normalizedTypes[i]); matrix.colNames.add(metadata.getColumnName(i + 1)); i++; } int count = 0; matrix.moreData = false; // while ((count++ < maxRecords || maxRecords < 0) && (matrix.moreData = result.next())) { Object[] rawrow = new Object[nbColumns]; i = 0; while (i < nbColumns) { Object value = result.getObject(i + 1); Object unbox = formatter.unboxJDBCObject(value, matrix.colTypes.get(i)); if (unbox instanceof String) { String stringVal = (String) unbox; rawrow[i] = DimensionValuesDictionary.INSTANCE.getRef(stringVal); } else { rawrow[i] = unbox; } i++; } matrix.addRow(new RawRow(rawrow)); count++; } long metter_finish = new Date().getTime(); if (logger.isDebugEnabled()) { logger.debug(("SQLQuery#" + item.getID() + "read " + (count - 1) + " row(s) in " + (metter_finish - metter_start) + " ms.")); } return matrix; } finally { item.close(); } }