List of usage examples for java.sql ResultSetMetaData getColumnName
String getColumnName(int column) throws SQLException;
From source file:org.apache.tajo.cli.DefaultTajoCliOutputFormatter.java
@Override public void printResult(PrintWriter sout, InputStream sin, TableDesc tableDesc, float responseTime, ResultSet res) throws Exception { long resultRows = tableDesc.getStats() == null ? -1 : tableDesc.getStats().getNumRows(); if (resultRows == -1) { resultRows = Integer.MAX_VALUE; }//from w w w . j a v a2s . c o m if (res == null) { sout.println(getQuerySuccessMessage(tableDesc, responseTime, 0, "inserted", true)); return; } ResultSetMetaData rsmd = res.getMetaData(); int numOfColumns = rsmd.getColumnCount(); for (int i = 1; i <= numOfColumns; i++) { if (i > 1) sout.print(", "); String columnName = rsmd.getColumnName(i); sout.print(columnName); } sout.println("\n-------------------------------"); int numOfPrintedRows = 0; int totalPrintedRows = 0; boolean endOfTuple = true; while (res.next()) { for (int i = 1; i <= numOfColumns; i++) { if (i > 1) sout.print(", "); String columnValue = res.getString(i); if (res.wasNull()) { sout.print(nullChar); } else { sout.print(columnValue); } } sout.println(); sout.flush(); numOfPrintedRows++; totalPrintedRows++; if (printPause && printPauseRecords > 0 && totalPrintedRows < resultRows && numOfPrintedRows >= printPauseRecords) { if (resultRows < Integer.MAX_VALUE) { sout.print("(" + totalPrintedRows + "/" + resultRows + " rows, continue... 'q' is quit)"); } else { sout.print("(" + totalPrintedRows + " rows, continue... 'q' is quit)"); } sout.flush(); if (sin != null) { if (sin.read() == 'q') { endOfTuple = false; sout.println(); break; } } numOfPrintedRows = 0; sout.println(); } } sout.println(getQuerySuccessMessage(tableDesc, responseTime, totalPrintedRows, "selected", endOfTuple)); sout.flush(); }
From source file:DatabaseBrowser.java
public ResultSetTableModel(ResultSet rset) throws SQLException { Vector rowData;/*from ww w . jav a 2 s. c o m*/ ResultSetMetaData rsmd = rset.getMetaData(); int count = rsmd.getColumnCount(); columnHeaders = new Vector(count); tableData = new Vector(); for (int i = 1; i <= count; i++) { columnHeaders.addElement(rsmd.getColumnName(i)); } while (rset.next()) { rowData = new Vector(count); for (int i = 1; i <= count; i++) { rowData.addElement(rset.getObject(i)); } tableData.addElement(rowData); } }
From source file:com.netspective.sparx.form.DialogContextUtils.java
public void populateFieldValuesFromResultSet(DialogContext dc, ResultSet rs) throws SQLException { if (rs.next()) { ResultSetMetaData rsmd = rs.getMetaData(); int colsCount = rsmd.getColumnCount(); DialogFieldStates fieldStates = dc.getFieldStates(); for (int i = 1; i <= colsCount; i++) { String fieldName = rsmd.getColumnName(i).toLowerCase(); DialogField.State state = fieldStates.getState(fieldName, null); if (state != null) { // for columns that are Date objects, use the object setter instead of the text setter // because we don't need to do unnecessary formatting/parsing if (rsmd.getColumnType(i) == Types.DATE) state.getValue().setValue(rs.getDate(i)); else state.getValue().setTextValue(rs.getString(i)); }// w w w.ja v a 2s .c o m } } }
From source file:net.sf.jdbcwrappers.trim.TrimmingResultSetWrapper.java
private void fetchCharColumns() throws SQLException { if (charColumns == null) { ResultSetMetaData metadata = getMetaData(); int columnCount = metadata.getColumnCount(); charColumns = new HashSet<String>(); isCharColumn = new boolean[columnCount]; for (int i = 1; i <= columnCount; i++) { if (metadata.getColumnType(i) == Types.CHAR) { charColumns.add(metadata.getColumnName(i).toUpperCase()); isCharColumn[i - 1] = true; }//from www .j a va2s. c o m } if (log.isDebugEnabled()) { log.debug("CHAR columns: " + charColumns); } } }
From source file:com.scistor.queryrouter.server.impl.JdbcHandlerImpl.java
@Override public Map<String, String> queryForMeta(String tableName) { long begin = System.currentTimeMillis(); Map<String, String> result = Maps.newConcurrentMap(); Connection conn = null;//from w w w . j a v a 2s . c o m PreparedStatement pst = null; try { conn = this.getJdbcTemplate().getDataSource().getConnection(); DatabaseMetaData dbMetaData = conn.getMetaData(); if (StringUtils.isNotEmpty(tableName)) { pst = conn.prepareStatement(String.format("select * from %s where 1=2", tableName)); ResultSetMetaData rsd = pst.executeQuery().getMetaData(); for (int i = 0; i < rsd.getColumnCount(); i++) { result.put(rsd.getColumnName(i + 1), rsd.getColumnTypeName(i + 1)); } } } catch (SQLException e1) { logger.error("queryId:{} select meta error:{}", 1, e1.getCause().getMessage()); } finally { JdbcUtils.closeConnection(conn); JdbcUtils.closeStatement(pst); logger.info("queryId:{} select meta cost:{} ms resultsize:{}", 1, System.currentTimeMillis() - begin, result.size()); } return result; }
From source file:org.apache.sqoop.connector.hbase.HbaseToInitializer.java
@Override public Schema getSchema(InitializerContext context, LinkConfiguration linkConfig, ToJobConfiguration toJobConfig) { executor = new HbaseExecutor(linkConfig.linkConfig); String schemaName = toJobConfig.toJobConfig.tableName; if (schemaName == null) { throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0019, "Table name extraction not supported yet."); }/* www. j a v a 2s . c o m*/ if (toJobConfig.toJobConfig.schemaName != null) { schemaName = toJobConfig.toJobConfig.schemaName + "." + schemaName; } Schema schema = new Schema(schemaName); ResultSet rs = null; ResultSetMetaData rsmt = null; try { rs = executor.executeQuery("SELECT * FROM " + schemaName + " WHERE 1 = 0"); rsmt = rs.getMetaData(); for (int i = 1; i <= rsmt.getColumnCount(); i++) { String columnName = rsmt.getColumnName(i); if (StringUtils.isEmpty(columnName)) { columnName = rsmt.getColumnLabel(i); if (StringUtils.isEmpty(columnName)) { columnName = "Column " + i; } } Column column = SqlTypesUtils.sqlTypeToSchemaType(rsmt.getColumnType(i), columnName, rsmt.getPrecision(i), rsmt.getScale(i)); schema.addColumn(column); } return schema; } catch (SQLException e) { throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0016, e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.info("Ignoring exception while closing ResultSet", e); } } } }
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);// w w w.j a v a 2s .c om } return rows; }
From source file:org.jtalks.poulpe.util.databasebackup.persistence.DbTableData.java
/** * The method prepares table's data in the shape and passes every {@link Row} into given RowProcessor. * //from w w w .j ava 2 s.c o m * @param processor * injected logic to perform some actions under passing rows. see details for {@link RowProcessor}. * @throws SQLException * if any errors during work with database occur. */ public void getData(final RowProcessor processor) throws SQLException { try { jdbcTemplate.query(SELECT_FROM + tableName, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); Row row = new Row(); for (int i = 1; i <= columnCount; i++) { ColumnMetaData columnMetaData = ColumnMetaData.getInstance(metaData.getColumnName(i), SqlTypes.getSqlTypeByJdbcSqlType(metaData.getColumnType(i))); row.addCell(columnMetaData, rs.getObject(i)); } try { processor.process(row); } catch (RowProcessingException e) { throw new SQLException(e); } } }); } catch (DataAccessException e) { throw new SQLException(e); } }
From source file:org.apache.hadoop.chukwa.extraction.Consolidator.java
public void run() { ResultSet rs = null;/*from www. j a v a2s . c o m*/ String[] columns; int[] columnsType; String groupBy = ""; for (int interval : intervals) { // Start reducing from beginning of time; Calendar aYearAgo = Calendar.getInstance(); aYearAgo.set(2008, 12, 30, 0, 0, 0); long start = aYearAgo.getTimeInMillis(); //starting from 2008/01/01 long end = start + (interval * 60000); log.debug("start time: " + start); log.debug("end time: " + end); Calendar now = Calendar.getInstance(); DatabaseWriter db = new DatabaseWriter(); String fields = null; String dateclause = null; boolean emptyPrimeKey = false; log.debug("Consolidate for " + interval + " minutes interval."); String table = this.table + "_" + interval; // Find the most recent entry try { String query = "select * from " + table + " order by timestamp desc limit 1"; log.debug("Query: " + query); rs = db.query(query); if (rs == null) { throw new SQLException("Table undefined."); } ResultSetMetaData rmeta = rs.getMetaData(); boolean empty = true; if (rs.next()) { for (int i = 1; i <= rmeta.getColumnCount(); i++) { if (rmeta.getColumnName(i).toLowerCase().equals("timestamp")) { start = rs.getTimestamp(i).getTime(); } } empty = false; } if (empty) { throw new SQLException("Table is empty."); } end = start + (interval * 60000); } catch (SQLException ex) { try { String query = "select * from " + this.table + " order by timestamp limit 1"; log.debug("Query: " + query); rs = db.query(query); if (rs.next()) { ResultSetMetaData rmeta = rs.getMetaData(); for (int i = 1; i <= rmeta.getColumnCount(); i++) { if (rmeta.getColumnName(i).toLowerCase().equals("timestamp")) { start = rs.getTimestamp(i).getTime(); } } } end = start + (interval * 60000); } catch (SQLException ex2) { log.error("Unable to determine starting point in table: " + this.table); log.error("SQL Error:" + ExceptionUtil.getStackTrace(ex2)); return; } } try { ResultSetMetaData rmeta = rs.getMetaData(); int col = rmeta.getColumnCount(); columns = new String[col]; columnsType = new int[col]; for (int i = 1; i <= col; i++) { columns[i - 1] = rmeta.getColumnName(i); columnsType[i - 1] = rmeta.getColumnType(i); } for (int i = 0; i < columns.length; i++) { if (i == 0) { fields = columns[i]; if (columnsType[i] == java.sql.Types.VARCHAR) { groupBy = " group by " + columns[i]; } } else { if (columnsType[i] == java.sql.Types.VARCHAR || columnsType[i] == java.sql.Types.TIMESTAMP) { fields = fields + "," + columns[i]; if (columnsType[i] == java.sql.Types.VARCHAR) { groupBy = " group by " + columns[i]; } } else { fields = fields + ",AVG(" + columns[i] + ") as " + columns[i]; } } } } catch (SQLException ex) { log.error("SQL Error:" + ExceptionUtil.getStackTrace(ex)); return; } if (groupBy.equals("")) { emptyPrimeKey = true; } long previousStart = start; while (end < now.getTimeInMillis() - (interval * 2 * 60000)) { // Select new data sample for the given intervals if (interval == 5) { table = this.table; } else if (interval == 30) { table = this.table + "_5"; } else if (interval == 120) { table = this.table + "_30"; } SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String startS = formatter.format(start); String endS = formatter.format(end); dateclause = "Timestamp >= '" + startS + "' and Timestamp <= '" + endS + "'"; if (emptyPrimeKey) { groupBy = "group by " + dateclause; } String query = "insert ignore into " + this.table + "_" + interval + " (select " + fields + " from " + table + " where " + dateclause + groupBy + ")"; log.debug(query); db.execute(query); db.close(); if (previousStart == start) { start = start + (interval * 60000); end = start + (interval * 60000); previousStart = start; } } } }
From source file:org.apache.hadoop.sqoop.manager.SqlManager.java
@Override public String[] getColumnNames(String tableName) { String stmt = "SELECT t.* FROM " + tableName + " AS t WHERE 1 = 1"; ResultSet results = execute(stmt); if (null == results) { return null; }/* w w w . j a v a2 s . com*/ try { int cols = results.getMetaData().getColumnCount(); ArrayList<String> columns = new ArrayList<String>(); ResultSetMetaData metadata = results.getMetaData(); for (int i = 1; i < cols + 1; i++) { String colName = metadata.getColumnName(i); if (colName == null || colName.equals("")) { colName = metadata.getColumnLabel(i); } columns.add(colName); } return columns.toArray(new String[0]); } catch (SQLException sqlException) { LOG.error("Error reading from database: " + sqlException.toString()); return null; } }