List of usage examples for java.sql ResultSetMetaData getColumnCount
int getColumnCount() throws SQLException;
ResultSet
object. From source file:gridool.util.csv.CsvWriter.java
public int writeAll(@Nonnull final ResultSet rs, @Nonnull final String nullStr, final boolean includeHeaders) throws SQLException { final ResultSetMetaData meta = rs.getMetaData(); if (includeHeaders) { writeColumnNames(meta);/*from w w w.j av a2 s . com*/ } final int numColumns = meta.getColumnCount(); final String[] columnClasses = new String[numColumns + 1]; for (int i = 1; i <= numColumns; i++) { String className = meta.getColumnClassName(i); columnClasses[i] = JAVA_STRING_CLASS_NAME.equals(className) ? JAVA_STRING_CLASS_NAME : className; } int numRows = 0; while (rs.next()) { for (int i = 1; i <= numColumns; i++) { if (i != 1) { write(separator); } final String column = rs.getString(i); if (column == null) { write(nullStr); } else if (JAVA_STRING_CLASS_NAME == columnClasses[i]) { // for speed optimization write(QUOTE); write(quoteData(column)); write(QUOTE); } else { write(column); } } write(lineSeparator); numRows++; } flush(); return numRows; }
From source file:com.piusvelte.hydra.MSSQLConnection.java
private JSONArray getResult(ResultSet rs) throws SQLException { JSONArray rows = new JSONArray(); ResultSetMetaData rsmd = rs.getMetaData(); String[] columnsArr = new String[rsmd.getColumnCount()]; for (int c = 0, l = columnsArr.length; c < l; c++) columnsArr[c] = rsmd.getColumnName(c); while (rs.next()) { JSONArray rowData = new JSONArray(); for (String column : columnsArr) rowData.add((String) rs.getObject(column)); rows.add(rowData);/*from w w w . j a va2 s.co m*/ } return rows; }
From source file:org.onebusaway.nyc.webapp.actions.admin.ReportingAction.java
public String submit() throws Exception { Session session = null;/*from www .j av a2 s. c om*/ Connection connection = null; Statement statement = null; ResultSet rs = null; try { session = sessionFactory.openSession(); connection = getConnectionFromSession(session); connection.setReadOnly(true); statement = connection.createStatement(); rs = statement.executeQuery(query); } catch (Exception e) { // make sure everything is closed if an exception was thrown try { rs.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } try { session.close(); } catch (Exception ex) { } reportError = e.getMessage(); // not really "success", but we'll use the same template with the error displayed return SUCCESS; } // final so the output generator thread can close it final Session finalSession = session; final Connection finalConnection = connection; final Statement finalStatement = statement; final ResultSet finalRS = rs; final PipedInputStream pipedInputStream = new PipedInputStream(); final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream); executorService.execute(new Runnable() { @Override public void run() { try { // column labels ResultSetMetaData metaData = finalRS.getMetaData(); int columnCount = metaData.getColumnCount(); for (int i = 0; i < columnCount; i++) { String columnName = metaData.getColumnName(i + 1); byte[] bytes = columnName.getBytes(); if (i > 0) pipedOutputStream.write(columnDelimiter); pipedOutputStream.write(bytes); } pipedOutputStream.write(newline); // column values while (finalRS.next()) { for (int i = 0; i < columnCount; i++) { String value = finalRS.getString(i + 1); if (value == null) value = "null"; else { // remove returns value = value.replaceAll("\n|\r", ""); } byte[] valueBytes = value.getBytes(); if (i > 0) pipedOutputStream.write(columnDelimiter); pipedOutputStream.write(valueBytes); } pipedOutputStream.write(newline); } } catch (Exception e) { } finally { try { pipedOutputStream.close(); } catch (IOException e) { } try { finalRS.close(); } catch (SQLException e) { } try { finalStatement.close(); } catch (SQLException e) { } try { finalConnection.close(); } catch (SQLException e) { } try { finalSession.close(); } catch (Exception e) { } } } }); // the input stream will get populated by the piped output stream inputStream = pipedInputStream; return "download"; }
From source file:com.thinkbiganalytics.schema.QueryRunner.java
/** * Initializes the query result with the specified metadata. * * @param queryResult the query result to initialize * @param rsMetaData the result set metadata for the query * @throws SQLException if the metadata is not available */// w ww. ja va2 s. co m private void initQueryResult(@Nonnull final DefaultQueryResult queryResult, @Nonnull final ResultSetMetaData rsMetaData) throws SQLException { final List<QueryResultColumn> columns = new ArrayList<>(); final Map<String, Integer> displayNameMap = new HashMap<>(); for (int i = 1; i <= rsMetaData.getColumnCount(); i++) { final 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.contains(displayName, ".") ? StringUtils.substringAfterLast(displayName, ".") : 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))); column.setNativeDataType(rsMetaData.getColumnTypeName(i)); columns.add(column); } queryResult.setColumns(columns); }
From source file:com.izv.controlador.ControladorAndroid.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*w ww . j a v a 2 s. c om*/ * * @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:kr.co.bitnine.octopus.engine.CursorByPass.java
private void execute(int numRows) throws PostgresException { if (getState() == State.DONE || getState() == State.FAILED) setState(State.READY);/* w w w . j a va 2 s . com*/ if (getState() != State.READY) return; LOG.debug("execute CursorByPass (rows=" + numRows + ")"); try { // NOTE: some JDBC drivers do not ignore setFetchSize(0) if (numRows > 0) stmt.setFetchSize(numRows); checkCancel(); ResultSet rs = stmt.executeQuery(); checkCancel(); ResultSetMetaData rsmd = rs.getMetaData(); int colCnt = rsmd.getColumnCount(); PostgresAttribute[] attrs = new PostgresAttribute[colCnt]; for (int i = 0; i < colCnt; i++) { String colName = rsmd.getColumnName(i + 1); int colType = rsmd.getColumnType(i + 1); LOG.info("JDBC type of column '" + colName + "' is " + colType); PostgresType type = TypeInfo.postresTypeOfJdbcType(colType); int typeInfo = -1; if (type == PostgresType.VARCHAR) typeInfo = rsmd.getColumnDisplaySize(i + 1); attrs[i] = new PostgresAttribute(colName, type, typeInfo); } tupDesc = new TupleDesc(attrs, getResultFormats()); tupSetByPass = new TupleSetByPass(this, rs, tupDesc); setState(State.ACTIVE); } catch (SQLException e) { setState(State.FAILED); close(); PostgresErrorData edata = new PostgresErrorData(PostgresSeverity.ERROR, "failed to execute by-pass query: " + e.getMessage()); throw new PostgresException(edata, e); } }
From source file:flex.messaging.io.ASRecordSet.java
public void populate(ResultSet rs) throws IOException { try {/*from ww w . ja v a 2 s. co m*/ ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); String[] columnNames = new String[columnCount]; int rowIndex = 0; List<List<Object>> initialData = new ArrayList<List<Object>>(); while (rs.next()) { rowIndex++; List<Object> row = new ArrayList<Object>(); for (int column = 0; column < columnCount; column++) { if (rowIndex == 1) { columnNames[column] = rsmd.getColumnName(column + 1); } row.add(rs.getObject(column + 1)); } if (rowIndex == 1) { setColumnNames(columnNames); } rows.add(row); if (rowIndex <= initialRowCount) { initialData.add(row); } } setTotalCount(rowIndex); setInitialData(initialData); setColumnNames(columnNames); } catch (SQLException e) { throw new IOException(e.getMessage()); } }
From source file:com.wantscart.jade.core.BeanPropertyRowMapper.java
/** * Extract the values for all columns in the current row. * <p/>/*from w ww .jav a2 s . co m*/ * Utilizes public setters and result set metadata. * * @see java.sql.ResultSetMetaData */ public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { // spring's : Object mappedObject = BeanUtils.instantiateClass(this.mappedClass); // jade's : private Object instantiateClass(this.mappedClass); // why: ??mappedClass.newInstranceBeanUtils.instantiateClass(mappedClass)1? Object mappedObject = instantiateClass(this.mappedClass); BeanWrapper bw = new BeanWrapperImpl(mappedObject); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); boolean warnEnabled = logger.isWarnEnabled(); boolean debugEnabled = logger.isDebugEnabled(); Set<String> populatedProperties = (checkProperties ? new HashSet<String>() : null); for (int index = 1; index <= columnCount; index++) { String columnName = JdbcUtils.lookupColumnName(rsmd, index).toLowerCase(); TableSchema.Column col = this.mappedFields.get(columnName); if (col != null) { try { Object value = JdbcUtils.getResultSetValue(rs, index, (Class<?>) col.getColumnType()); if (debugEnabled && rowNumber == 0) { logger.debug("Mapping column '" + columnName + "' to property '" + col.getName() + "' of type " + col.getType()); } if (col.isSerializable()) { if (col.getSerializer().getClass() != NullSerializer.class) { value = col.getSerializer().deserialize(value, col.getGenericType() != null ? col.getGenericType() : col.getType()); } else { Serializable instance = (Serializable) BeanUtils .instantiateClass((Class) col.getType()); instance.deserialize(value); value = instance; } } bw.setPropertyValue(col.getOriginName(), value); if (populatedProperties != null) { populatedProperties.add(col.getName()); } } catch (NotWritablePropertyException ex) { throw new DataRetrievalFailureException( "Unable to map column " + columnName + " to property " + col.getOriginName(), ex); } } else { if (checkColumns) { throw new InvalidDataAccessApiUsageException("Unable to map column '" + columnName + "' to any properties of bean " + this.mappedClass.getName()); } if (warnEnabled && rowNumber == 0) { logger.warn("Unable to map column '" + columnName + "' to any properties of bean " + this.mappedClass.getName()); } } } if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) { throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties); } return mappedObject; }
From source file:com.mvdb.etl.dao.impl.JdbcGenericDAO.java
@Override public void fetchMetadata(String objectName, File snapshotDirectory) { final Metadata metadata = new Metadata(); metadata.setTableName(objectName);/*from www . jav a 2s . c o m*/ String sql = "SELECT * FROM " + objectName + " limit 1"; final Map<String, ColumnMetadata> metaDataMap = new HashMap<String, ColumnMetadata>(); metadata.setColumnMetadataMap(metaDataMap); metadata.setTableName(objectName); getJdbcTemplate().query(sql, new RowCallbackHandler() { @Override public void processRow(ResultSet row) throws SQLException { ResultSetMetaData rsm = row.getMetaData(); int columnCount = rsm.getColumnCount(); for (int column = 1; column < (columnCount + 1); column++) { ColumnMetadata columnMetadata = new ColumnMetadata(); columnMetadata.setColumnLabel(rsm.getColumnLabel(column)); columnMetadata.setColumnName(rsm.getColumnName(column)); columnMetadata.setColumnType(rsm.getColumnType(column)); columnMetadata.setColumnTypeName(rsm.getColumnTypeName(column)); metaDataMap.put(rsm.getColumnName(column), columnMetadata); } } }); writeMetadata(metadata, snapshotDirectory); }
From source file:com.mx.core.dao.BeanPropRowMap.java
/** * Extract the values for all columns in the current row. * <p>Utilizes public setters and result set metadata. * @see java.sql.ResultSetMetaData// www . j a v a 2s. com */ public T mapRow(ResultSet rs, int rowNumber) throws SQLException { Assert.state(this.mappedClass != null, "Mapped class was not specified"); T mappedObject = BeanUtils.instantiate(this.mappedClass); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject); initBeanWrapper(bw); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null); for (int index = 1; index <= columnCount; index++) { String column = JdbcUtils.lookupColumnName(rsmd, index); PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase()); if (pd != null) { try { Object value = getColumnValue(rs, index, pd); if (logger.isDebugEnabled() && rowNumber == 0) { //logger.debug("Mapping column '" + column + "' to property '" + // pd.getName() + "' of type " + pd.getPropertyType()); } try { bw.setPropertyValue(pd.getName(), value); } catch (TypeMismatchException e) { if (value == null && primitivesDefaultedForNullValue) { logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '" + column + "' with value " + value + " when setting property '" + pd.getName() + "' of type " + pd.getPropertyType() + " on object: " + mappedObject); } else { throw e; } } if (populatedProperties != null) { populatedProperties.add(pd.getName()); } } catch (NotWritablePropertyException ex) { throw new DataRetrievalFailureException( "Unable to map column " + column + " to property " + pd.getName(), ex); } } } if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) { throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties); } return mappedObject; }