List of usage examples for java.sql ResultSet getMetaData
ResultSetMetaData getMetaData() throws SQLException;
ResultSet
object's columns. From source file:com.twosigma.beakerx.sql.QueryExecutor.java
private QueryResult executeQuery(int currentIterationIndex, BeakerParseResult queryLine, Connection conn, BeakerXClient 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;/*from w w w . ja va 2 s . c o m*/ 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; }
From source file:com.tesora.dve.client.ClientTestNG.java
@Test public void infoSchemaColumnMetadataTest() throws Exception { StringBuffer query = new StringBuffer().append("SHOW DATABASES"); dbHelper.executeQuery(query.toString()); ResultSet rs = dbHelper.getResultSet(); ResultSetMetaData rsmd = rs.getMetaData(); // make sure the column header is not empty assertTrue(!StringUtils.isEmpty(rsmd.getColumnLabel(1))); assertEquals(ShowSchema.Database.NAME, rsmd.getColumnLabel(1)); }
From source file:teambootje.A2.java
public A2() { initComponents();//from w w w .ja va 2s.c o m setLocationRelativeTo(null); setLayout(new BorderLayout()); //Create and set up the window. setTitle("SS Rotterdam Analyse || Analyse 2"); 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 Datum, COUNT(*) AS Aantal FROM posts GROUP BY Datum"; List<Object[]> list = new ArrayList<Object[]>(); ResultSet rs = null; try { rs = db.runSql(sql); while (rs.next()) { String datum = rs.getString("Datum"); int aantal = 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 dat = datum; int a1 = aantal; @Override public void actionPerformed(ActionEvent e) { DefaultPieDataset pieDataset = new DefaultPieDataset(); pieDataset.setValue(dat, a1); pieDataset.setValue("2015-04-06", new Integer(5)); pieDataset.setValue("2015-04-05", new Integer(5)); pieDataset.setValue("2015-04-04", new Integer(14)); pieDataset.setValue("2015-04-03", new Integer(4)); pieDataset.setValue("2015-04-02", new Integer(1)); pieDataset.setValue("2015-04-01", new Integer(32)); pieDataset.setValue("2015-03-31", new Integer(32)); pieDataset.setValue("2015-03-30", new Integer(9)); pieDataset.setValue("2015-03-29", new Integer(4)); pieDataset.setValue("2015-03-28", new Integer(1)); pieDataset.setValue("2015-03-27", new Integer(3)); pieDataset.setValue("2015-03-26", new Integer(6)); pieDataset.setValue("2015-03-25", new Integer(1)); pieDataset.setValue("2015-03-24", new Integer(1)); pieDataset.setValue("2015-03-23", new Integer(1)); pieDataset.setValue("2015-03-22", new Integer(1)); pieDataset.setValue("2015-03-21", new Integer(1)); pieDataset.setValue("2015-03-20", new Integer(1)); pieDataset.setValue("2015-03-19", new Integer(1)); pieDataset.setValue("2015-03-18", new Integer(2)); pieDataset.setValue("2015-03-17", new Integer(1)); JFreeChart chart = ChartFactory.createPieChart3D("Aantal Posts per datum", pieDataset, true, true, true); PiePlot3D p = (PiePlot3D) chart.getPlot(); //p.setForegroundAlpha(TOP_ALIGNMENT); ChartFrame pie = new ChartFrame("Aantal Posts per datum", 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[] = { "Datum", "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.izv.controlador.ControladorAndroid.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w. jav a2s . c o m * * @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:it.unibas.spicy.persistence.csv.ExportCSVInstances.java
public void createCSVDocument(String tableName, String schema, IDataSourceProxy dataSourceTarget, String folderPath, Statement statement, String[] columnNames, boolean unpivot) throws SQLException, IOException { File file = new File(folderPath + File.separator + tableName + ".csv"); ResultSet allRows = statement.executeQuery("SELECT * FROM " + schema + ".\"" + tableName + "\";"); int columnCount = allRows.getMetaData().getColumnCount(); if (columnNames == null) { //first write column names columnNames = new String[columnCount]; int i = 0; //datasource is null when exporting the unpivoted csv table if (dataSourceTarget != null) { INode tableNode = dataSourceTarget.getIntermediateSchema().getChild(tableName); //get column names from the first table tuple only for (INode column : tableNode.getChild(0).getChildren()) { String columnLabel = column.getLabel(); String oldValue = dataSourceTarget.getChangedValue(tableName + "." + columnLabel); if (oldValue != null) { columnNames[i] = oldValue; } else { columnNames[i] = columnLabel; }//from w w w . j a v a2 s .co m i++; } } } CSVWriter csvWriter = new CSVWriter(new FileWriter(file), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER); csvWriter.writeNext(columnNames, false); try { //then write the data while (allRows.next()) { String[] row = new String[columnCount]; for (int j = 1; j <= columnCount; j++) { String dataType = allRows.getMetaData().getColumnTypeName(j); String value = allRows.getString(j); //if the value is null write null to csv file if (value == null) { //avenet 20170721 - here we can export either null or ,,. Postgres treats them the same - we export ,, because it is more correct //avenet 20170215 null values in Postgres csv mode correspond to ,, value = ""; // value = "null"; } //if the type is String/text etc and is not null put the value between double quotes else if (dataType.toLowerCase().startsWith("varchar") || dataType.toLowerCase().startsWith("char") || dataType.toLowerCase().startsWith("text") || dataType.equalsIgnoreCase("bpchar") || dataType.equalsIgnoreCase("bit") || dataType.equalsIgnoreCase("mediumtext") || dataType.equalsIgnoreCase("longtext") || dataType.equalsIgnoreCase("serial") || dataType.equalsIgnoreCase("enum")) { //avenet 20170724 - by adding these double quotes string values are stored in the form ,"value", and nulls as ,, value = "\"" + value + "\""; } row[j - 1] = value; } //the following false value means there will not be quotes added, since we have already added double quotes only for string results csvWriter.writeNext(row, false); } } finally { csvWriter.close(); allRows.close(); } }
From source file:com.handu.open.dubbo.monitor.dao.base.DubboInvokeBaseDAO.java
/** * SQL?// w w w . ja v a 2 s .c o m * * @param sql SQL? * @return List<Map> */ public List<Map> querySql(String sql) { List<Map> list = Lists.newArrayList(); try { ResultSet rs = getSqlSession().getConnection() .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery(); try { ResultSetMetaData rsm = rs.getMetaData(); // int col = rsm.getColumnCount(); // String[] colName = new String[col]; //???, colName for (int i = 0; i < col; i++) { colName[i] = rsm.getColumnName(i + 1); } rs.beforeFirst(); while (rs.next()) { Map<String, String> map = Maps.newHashMap(); for (String aColName : colName) { map.put(aColName, rs.getString(aColName)); } list.add(map); } } catch (SQLException e) { e.printStackTrace(); return null; } } catch (SQLException e) { e.printStackTrace(); } return list; }
From source file:com.mvdb.etl.dao.impl.JdbcGenericDAO.java
@Override public DataHeader fetchAll2(File snapshotDirectory, Timestamp modifiedAfter, String objectName, final String keyName, final String updateTimeColumnName) { File objectFile = new File(snapshotDirectory, "data-" + objectName + ".dat"); final GenericConsumer genericConsumer = new SequenceFileConsumer(objectFile); final DataHeader dataHeader = new DataHeader(); String sql = "SELECT * FROM " + objectName + " o where o.update_time >= ?"; getJdbcTemplate().query(sql, new Object[] { modifiedAfter }, new RowCallbackHandler() { @Override//from w w w . ja va 2 s. c o m public void processRow(ResultSet row) throws SQLException { final Map<String, Object> dataMap = new HashMap<String, Object>(); ResultSetMetaData rsm = row.getMetaData(); int columnCount = rsm.getColumnCount(); for (int column = 1; column < (columnCount + 1); column++) { dataMap.put(rsm.getColumnName(column), row.getObject(rsm.getColumnLabel(column))); } DataRecord dataRecord = new GenericDataRecord(dataMap, keyName, globalMvdbKeyMaker, updateTimeColumnName, new GlobalMvdbUpdateTimeMaker()); genericConsumer.consume(dataRecord); dataHeader.incrementCount(); } }); genericConsumer.flushAndClose(); writeDataHeader(dataHeader, objectName, snapshotDirectory); return dataHeader; }
From source file:com.twosigma.beaker.sqlsh.utils.QueryExecutor.java
private QueryResult executeQuery(int currentIterationIndex, BeakerParseResult queryLine, Connection conn, NamespaceClient namespaceClient) throws SQLException, ReadVariableException { QueryResult queryResult = new QueryResult(); String sql = queryLine.getResultQuery(); try (Statement statement = conn.createStatement()) { this.statement = statement; for (BeakerInputVar parameter : queryLine.getInputVars()) { if (parameter.getErrorMessage() != null) throw new ReadVariableException(parameter.getErrorMessage()); Object obj;//w ww .ja v a 2s.c o m try { obj = namespaceClient.get(parameter.objectName); if (!parameter.isArray() && !parameter.isObject()) { sql = setObject(sql, obj); } else if (!parameter.isArray() && parameter.isObject()) { sql = setObject(sql, 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) { sql = setObject(sql, ((List) obj).get(index)); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); sql = setObject(sql, arrayElement); } } else { if (obj instanceof List) { sql = setObject(sql, getValue(((List) obj).get(index), parameter.getFieldName())); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); sql = setObject(sql, getValue(arrayElement, parameter.getFieldName())); } } } } catch (Exception e) { throw new ReadVariableException(parameter.objectName, e); } } boolean hasResultSet = statement.execute(sql); 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; }
From source file:com.sangupta.fileanalysis.db.DBResultViewer.java
/** * View resutls of a {@link ResultSet}./*from w w w. j a v a 2 s . c o m*/ * * @param resultSet * @throws SQLException */ public void viewResult(ResultSet resultSet) throws SQLException { if (resultSet == null) { // nothing to do return; } // collect the meta ResultSetMetaData meta = resultSet.getMetaData(); final int numColumns = meta.getColumnCount(); final int[] displaySizes = new int[numColumns + 1]; final int[] colType = new int[numColumns + 1]; for (int index = 1; index <= numColumns; index++) { colType[index] = meta.getColumnType(index); displaySizes[index] = getColumnSize(meta.getTableName(index), meta.getColumnName(index), colType[index]); } // display the header row for (int index = 1; index <= numColumns; index++) { center(meta.getColumnLabel(index), displaySizes[index]); } System.out.println("|"); for (int index = 1; index <= numColumns; index++) { System.out.print("+" + StringUtils.repeat('-', displaySizes[index] + 2)); } System.out.println("+"); // start iterating over the result set int rowsDisplayed = 0; int numRecords = 0; while (resultSet.next()) { // read and display the value rowsDisplayed++; numRecords++; for (int index = 1; index <= numColumns; index++) { switch (colType[index]) { case Types.DECIMAL: case Types.DOUBLE: case Types.REAL: format(resultSet.getDouble(index), displaySizes[index]); continue; case Types.INTEGER: case Types.SMALLINT: format(resultSet.getInt(index), displaySizes[index]); continue; case Types.VARCHAR: format(resultSet.getString(index), displaySizes[index], false); continue; case Types.TIMESTAMP: format(resultSet.getTimestamp(index), displaySizes[index]); continue; case Types.BIGINT: format(resultSet.getBigDecimal(index), displaySizes[index]); continue; } } // terminator for row and new line System.out.println("|"); // check for rows displayed if (rowsDisplayed == 20) { // ask the user if more data needs to be displayed String cont = ConsoleUtils.readLine("Type \"it\" for more: ", true); if (!"it".equalsIgnoreCase(cont)) { break; } // continue; rowsDisplayed = 0; continue; } } System.out.println("\nTotal number of records found: " + numRecords); }
From source file:com.gdo.project.util.SqlUtils.java
@Deprecated public static InputStream e4xFacet(StclContext stclContext, String query, char sep, char newLine) { if (StringUtils.isEmpty(query)) { if (getLog().isWarnEnabled()) { getLog().warn(stclContext, "SqlUtils:e4xFacet empty query..."); }/* w w w . j a v a2s . c o m*/ return StringHelper.EMPTY_STRING_INPUT_STREAM; } try { ResultSet rs = query(stclContext, query); if (rs != null) { StringBuffer e4x = new StringBuffer(); boolean first = true; while (rs.next()) { int cols = rs.getMetaData().getColumnCount(); // write column title if (first) { for (int j = 1; j <= cols; j++) { e4x.append(String.format("%s", rs.getMetaData().getColumnName(j))); if (j < cols) e4x.append(sep); } e4x.append(newLine); } // write row content for (int j = 1; j <= cols; j++) { e4x.append(String.format("%s", rs.getString(j))); if (j < cols) e4x.append(sep); } e4x.append(newLine); first = false; } return new ByteArrayInputStream(e4x.toString().getBytes()); } } catch (SQLException e) { if (getLog().isWarnEnabled()) { getLog().warn(stclContext, "SqlUtils:e4xFacet error", e); } } return StringHelper.EMPTY_STRING_INPUT_STREAM; }