List of usage examples for java.sql ResultSet getMetaData
ResultSetMetaData getMetaData() throws SQLException;
ResultSet
object's columns. From source file:teambootje.A8.java
/** * Creates new form A8//from w w w .j a va 2 s. c om */ public A8() { initComponents(); setLocationRelativeTo(null); setLayout(new BorderLayout()); //Create and set up the window. setTitle("SS Rotterdam Analyse || Analyse 8"); ImageIcon icon = new ImageIcon("img/bootje.jpg"); setIconImage(icon.getImage()); // back BTN JButton back = new JButton("Back"); add(back, BorderLayout.NORTH); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); // panel en Label JPanel ana = new JPanel(); add(ana, BorderLayout.CENTER); //tabel String sql = "SELECT doelgroep.Doelgroep, COUNT(posts.post) AS Aantal FROM doelgroep, posts WHERE posts.DID = doelgroep.DID GROUP BY doelgroep.Doelgroep"; List<Object[]> list = new ArrayList<Object[]>(); ResultSet rs = null; try { rs = db.runSql(sql); while (rs.next()) { String ta = rs.getString("doelgroep.Doelgroep"); int amount = rs.getInt("Aantal"); String[] row = new String[rs.getMetaData().getColumnCount()]; for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { row[i - 1] = rs.getString(i); } list.add(row); //chart JButton chart = new JButton("Chart"); add(chart, BorderLayout.SOUTH); chart.addActionListener(new ActionListener() { String dd = ta; int a1 = amount; @Override public void actionPerformed(ActionEvent e) { DefaultPieDataset pieDataset = new DefaultPieDataset(); pieDataset.setValue(dd, a1); pieDataset.setValue("50+", new Integer(0)); pieDataset.setValue("Tiener", new Integer(0)); pieDataset.setValue("40+", new Integer(0)); pieDataset.setValue("30+", new Integer(0)); JFreeChart chart = ChartFactory.createPieChart3D("Aantal Posts per doelgroep", pieDataset, true, true, true); PiePlot3D p = (PiePlot3D) chart.getPlot(); //p.setForegroundAlpha(TOP_ALIGNMENT); ChartFrame pie = new ChartFrame("Aantal Posts per doelgroep", chart); pie.setVisible(true); pie.setSize(500, 500); pie.setLocationRelativeTo(null); //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, e); } Object[][] array = new Object[list.size()][]; Object columnNames[] = { "Doelgoep", "Aantal" }; list.toArray(array); JTable table = new JTable(array, columnNames); JScrollPane scroll = new JScrollPane(table); scroll.setPreferredSize(new Dimension(400, 400)); ana.add(scroll); }
From source file:com.netspective.sparx.sql.QueryResultSetDataSource.java
protected void setResultSet(ResultSet resultSet) { this.resultSet = queryResultSet.getResultSet(); try {/* www . j a va 2s . co m*/ if (cacheColumnData) { final ResultSetMetaData metaData = resultSet.getMetaData(); retrievedColumnData = new boolean[metaData.getColumnCount()]; cachedColumnData = new Object[metaData.getColumnCount()]; } scrollable = resultSet.getType() != ResultSet.TYPE_FORWARD_ONLY ? true : false; } catch (SQLException e) { log.error("Unable to set result set", e); throw new NestableRuntimeException(e); } activeRowIndex = -1; calculatedTotalRows = false; }
From source file:com.svds.resttest.services.GenericDataService.java
/** * Obtain metaDataSet from rs and add to genericResultsOutput * /*from w w w.j av a2s. 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.dsf.dbxtract.cdc.journal.JournalExecutor.java
/** * Retrieve column names from a resultset * /*from w w w . j ava2 s. c o m*/ * @param rs * query result set * @return array of column names * @throws SQLException */ private String[] getColumnNamesFromResultSet(ResultSet rs) throws SQLException { int cols = rs.getMetaData().getColumnCount(); String[] colNames = new String[cols]; for (int i = 0; i < cols; i++) { colNames[i] = rs.getMetaData().getColumnLabel(i + 1); } return colNames; }
From source file:org.jfree.data.jdbc.JDBCPieDataset.java
/** * ExecuteQuery will attempt execute the query passed to it against the * existing database connection. If no connection exists then no action * is taken.//from w ww .j av a 2 s . com * The results from the query are extracted and cached locally, thus * applying an upper limit on how many rows can be retrieved successfully. * * @param query the query to be executed * @param con the connection the query is to be executed against * * @throws SQLException if there is a problem executing the query. */ public void executeQuery(Connection con, String query) throws SQLException { Statement statement = null; ResultSet resultSet = null; try { statement = con.createStatement(); resultSet = statement.executeQuery(query); ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); if (columnCount != 2) { throw new SQLException("Invalid sql generated. PieDataSet requires 2 columns only"); } int columnType = metaData.getColumnType(2); double value = Double.NaN; while (resultSet.next()) { Comparable key = resultSet.getString(1); switch (columnType) { case Types.NUMERIC: case Types.REAL: case Types.INTEGER: case Types.DOUBLE: case Types.FLOAT: case Types.DECIMAL: case Types.BIGINT: value = resultSet.getDouble(2); setValue(key, value); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: Timestamp date = resultSet.getTimestamp(2); value = date.getTime(); setValue(key, value); break; default: System.err.println("JDBCPieDataset - unknown data type"); break; } } fireDatasetChanged(new DatasetChangeInfo()); //TODO: fill in real change info } finally { if (resultSet != null) { try { resultSet.close(); } catch (Exception e) { System.err.println("JDBCPieDataset: swallowing exception."); } } if (statement != null) { try { statement.close(); } catch (Exception e) { System.err.println("JDBCPieDataset: swallowing exception."); } } } }
From source file:com.pymmasoftware.platform.login.loginmodule.DroolsLoginModule.java
@Override public boolean login() throws LoginException { succeeded = false;/* ww w . j a va 2s . com*/ QueryRunner queryRunner = null; try { userPrincipal = null; roles = null; if (callbackHandler == null) throw new LoginException("No callback handler"); NameCallback nameCallback = new NameCallback("Username"); PasswordCallback passwordCallback = new PasswordCallback("Password", false); Callback[] callbacks = new Callback[] { nameCallback, passwordCallback }; try { callbackHandler.handle(callbacks); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedCallbackException e) { // TODO Auto-generated catch block e.printStackTrace(); } username = nameCallback.getName(); password = new String(passwordCallback.getPassword()); queryRunner = new QueryRunner(dataSource); // Create a ResultSetHandler implementation to convert the // first row into an Object[]. ResultSetHandler<DroolsPrincipal> h = new ResultSetHandler<DroolsPrincipal>() { public DroolsPrincipal handle(ResultSet rs) throws SQLException { if (!rs.next()) { return null; } ResultSetMetaData meta = rs.getMetaData(); String userName = rs.getString("username"); DroolsPrincipal droolsPrincipal = new DroolsPrincipal(userName); droolsPrincipal.setId(rs.getInt("id")); return droolsPrincipal; } }; ResultSetHandler<List<String>> hh = new ResultSetHandler<List<String>>() { public List<String> handle(ResultSet rs) throws SQLException { if (!rs.next()) { return null; } List<String> droolsGroups = new ArrayList<>(); boolean goOne = true; while (goOne) { String groupName = rs.getString("groups"); droolsGroups.add(groupName); if (rs.next() == false) { goOne = false; } } return droolsGroups; } }; String sqlname = "select * from guvnorusers where username = ? and password = ? "; DroolsPrincipal user = queryRunner.query(sqlname, h, username, password); if (user == null) { succeeded = false; throw new FailedLoginException("The username or The password is incorrect"); } else { userPrincipal = user; String sqlname2 = "select groups from guvnorgroups gr,guvnorusers_groups gr_user " + "where gr.id = gr_user.groups_id " + "and gr_user.guvnorusers_id= ?"; List<String> droolsGroups = queryRunner.query(sqlname2, hh, user.getId()); if (droolsGroups != null) { int i = droolsGroups.size(); roles = new String[i]; i = 0; for (String droolsGroup : droolsGroups) { roles[i] = droolsGroup; i++; } } succeeded = true; return true; } } catch (Exception e) { throw new LoginException(e.getMessage()); } finally { queryRunner = null; } }
From source file:architecture.common.adaptor.connector.jdbc.AbstractJdbcConnector.java
protected List<Map<String, Object>> pull(final String queryString, final List<ParameterMapping> parameterMappings, final Object[] args) { // log.debug("pulling..." ); return getJdbcTemplate().query(queryString, args, new RowMapper<Map<String, Object>>() { public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); Map<String, Object> mapOfColValues = createColumnMap(columnCount); for (int i = 1; i <= columnCount; i++) { String key = getColumnKey(lookupColumnName(rsmd, i)); Object obj = getColumnValue(rs, i); mapOfColValues.put(key, obj); }/*from www . ja v a2 s.c o m*/ return mapOfColValues; } protected Map<String, Object> createColumnMap(int columnCount) { return new LinkedHashMap<String, Object>(columnCount); } protected String getColumnKey(String columnName) { return columnName; } protected Object getColumnValue(ResultSet rs, int index) throws SQLException { for (ParameterMapping mapping : parameterMappings) { // LOG.debug( index + " mapping match :" + // mapping.getIndex()); if (index == mapping.getIndex()) { if (String.class == mapping.getJavaType()) { String value = rs.getString(index); if (StringUtils.isEmpty(value)) value = ""; if (!StringUtils.isEmpty(mapping.getCipher())) { try { Cipher cipher = Cipher.getInstance(mapping.getCipher()); SecretKeySpec skeySpec = new SecretKeySpec( Hex.decodeHex(mapping.getCipherKey().toCharArray()), mapping.getCipherKeyAlg()); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte raw[]; if (!StringUtils.isEmpty(mapping.getEncoding())) { String enc = mapping.getEncoding(); if (enc.toUpperCase().equals("BASE64")) { raw = Base64.decodeBase64(value); // BASE64Decoder decoder = new // BASE64Decoder(); // raw = // decoder.decodeBuffer(value); } else { raw = value.getBytes(); } } else { raw = value.getBytes(); } byte stringBytes[] = cipher.doFinal(raw); return new String(stringBytes); } catch (Exception e) { LOG.error(e); } return value; } if (!StringUtils.isEmpty(mapping.getEncoding())) { String[] encoding = StringUtils.split(mapping.getEncoding(), ">"); try { if (encoding.length == 2) return new String(value.getBytes(encoding[0]), encoding[1]); else if (encoding.length == 1) { return new String(value.getBytes(), encoding[0]); } } catch (UnsupportedEncodingException e) { LOG.error(e); return value; } } } else if (Long.class == mapping.getJavaType()) { String value = rs.getString(index); if (StringUtils.isEmpty(value)) value = "0"; return new Long(value); } else if (Integer.class == mapping.getJavaType()) { String value = rs.getString(index); if (StringUtils.isEmpty(value)) value = "0"; return new Integer(value); } else if (Double.class == mapping.getJavaType()) { String value = rs.getString(index); if (StringUtils.isEmpty(value)) value = "0"; return new Double(value); } } } return JdbcUtils.getResultSetValue(rs, index); } }); }
From source file:chh.utils.db.source.common.JdbcClient.java
public List<List<Column>> select(String sqlQuery, List<Column> queryParams) { Connection connection = null; try {// w ww . j a va2s . c o m connection = connectionProvider.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery); if (queryTimeoutSecs > 0) { preparedStatement.setQueryTimeout(queryTimeoutSecs); } setPreparedStatementParams(preparedStatement, queryParams); ResultSet resultSet = preparedStatement.executeQuery(); List<List<Column>> rows = Lists.newArrayList(); while (resultSet.next()) { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); List<Column> row = Lists.newArrayList(); for (int i = 1; i <= columnCount; i++) { String columnLabel = metaData.getColumnLabel(i); int columnType = metaData.getColumnType(i); Class columnJavaType = Util.getJavaType(columnType); if (columnJavaType.equals(String.class)) { row.add(new Column<String>(columnLabel, resultSet.getString(columnLabel), columnType)); } else if (columnJavaType.equals(Integer.class)) { row.add(new Column<Integer>(columnLabel, resultSet.getInt(columnLabel), columnType)); } else if (columnJavaType.equals(Double.class)) { row.add(new Column<Double>(columnLabel, resultSet.getDouble(columnLabel), columnType)); } else if (columnJavaType.equals(Float.class)) { row.add(new Column<Float>(columnLabel, resultSet.getFloat(columnLabel), columnType)); } else if (columnJavaType.equals(Short.class)) { row.add(new Column<Short>(columnLabel, resultSet.getShort(columnLabel), columnType)); } else if (columnJavaType.equals(Boolean.class)) { row.add(new Column<Boolean>(columnLabel, resultSet.getBoolean(columnLabel), columnType)); } else if (columnJavaType.equals(byte[].class)) { row.add(new Column<byte[]>(columnLabel, resultSet.getBytes(columnLabel), columnType)); } else if (columnJavaType.equals(Long.class)) { row.add(new Column<Long>(columnLabel, resultSet.getLong(columnLabel), columnType)); } else if (columnJavaType.equals(Date.class)) { row.add(new Column<Date>(columnLabel, resultSet.getDate(columnLabel), columnType)); } else if (columnJavaType.equals(Time.class)) { row.add(new Column<Time>(columnLabel, resultSet.getTime(columnLabel), columnType)); } else if (columnJavaType.equals(Timestamp.class)) { row.add(new Column<Timestamp>(columnLabel, resultSet.getTimestamp(columnLabel), columnType)); } else { throw new RuntimeException( "type = " + columnType + " for column " + columnLabel + " not supported."); } } rows.add(row); } return rows; } catch (SQLException e) { throw new RuntimeException("Failed to execute select query " + sqlQuery, e); } finally { closeConnection(connection); } }
From source file:com.abixen.platform.service.businessintelligence.multivisualisation.service.impl.AbstractDatabaseService.java
private DataValueWeb getDataFromColumn(ResultSet row, String columnName) { try {//from www. j av a 2 s .c o m ResultSetMetaData resultSetMetaData = row.getMetaData(); String columnTypeName = getValidColumnTypeName(row.findColumn(columnName), resultSetMetaData); return getValueAsDataSourceValue(row, columnName, DataValueType.valueOf(columnTypeName)); } catch (SQLException e) { throw new DataSourceValueException("Error when getting value from column. " + e.getMessage()); } }
From source file:com.twosigma.beaker.sql.QueryExecutor.java
private QueryResult executeQuery(int currentIterationIndex, BeakerParseResult queryLine, Connection conn, NamespaceClient namespaceClient) throws SQLException, ReadVariableException { QueryResult queryResult = new QueryResult(); try (PreparedStatement statement = conn.prepareStatement(queryLine.getResultQuery())) { this.statement = statement; int n = 1; for (BeakerInputVar parameter : queryLine.getInputVars()) { if (parameter.getErrorMessage() != null) throw new ReadVariableException(parameter.getErrorMessage()); Object obj;//ww w.j av a2 s . c om try { obj = namespaceClient.get(parameter.objectName); if (!parameter.isArray() && !parameter.isObject()) { statement.setObject(n, obj); } else if (!parameter.isArray() && parameter.isObject()) { statement.setObject(n, getValue(obj, parameter.getFieldName())); } else if (parameter.isArray()) { int index; if (currentIterationIndex > 0 && parameter.isAll()) { index = currentIterationIndex; } else { index = parameter.index; } if (!parameter.isObject()) { if (obj instanceof List) { statement.setObject(n, ((List) obj).get(index)); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); statement.setObject(n, arrayElement); } } else { if (obj instanceof List) { statement.setObject(n, getValue(((List) obj).get(index), parameter.getFieldName())); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); statement.setObject(n, getValue(arrayElement, parameter.getFieldName())); } } } n++; } catch (Exception e) { throw new ReadVariableException(parameter.objectName, e); } } boolean hasResultSet = statement.execute(); if (hasResultSet) { ResultSet rs = statement.getResultSet(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { queryResult.getColumns().add(rs.getMetaData().getColumnName(i)); queryResult.getTypes().add(rs.getMetaData().getColumnClassName(i)); } while (rs.next()) { if (rs.getMetaData().getColumnCount() != 0) { List<Object> row = new ArrayList<Object>(); queryResult.getValues().add(row); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { if (java.sql.Date.class.getName().equals(rs.getMetaData().getColumnClassName(i))) { java.sql.Date sqlDate = rs.getDate(i); row.add(sqlDate == null ? null : new Date(sqlDate.getTime())); } else { row.add(rs.getObject(i)); } } } } } } catch (SQLException e) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e); try { conn.rollback(); } catch (Exception e1) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e1); } throw e; } return queryResult; }