List of usage examples for java.sql ResultSetMetaData getColumnLabel
String getColumnLabel(int column) throws SQLException;
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);// w w w . 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: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; }//from w w w . j a va 2 s . c o m 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; } }
From source file:org.apache.kylin.rest.util.HiveReroute.java
private void extractColumnMetadata(ResultSet resultSet, List<SelectedColumnMeta> columnMetas) throws SQLException { ResultSetMetaData metaData = null; int columnCount = 0; metaData = resultSet.getMetaData();/* w w w . ja v a 2 s. co m*/ columnCount = metaData.getColumnCount(); // fill in selected column meta for (int i = 1; i <= columnCount; ++i) { columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i), false, metaData.isCurrency(i), metaData.isNullable(i), false, metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i), null, null, null, metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i), false, false)); } }
From source file:com.diversityarrays.dal.server.SqlDialog.java
public int doSqlQuery(ResultSet rs, List<String> headings, List<String[]> rows) throws SQLException { int nColumns = -1; while (rs.next()) { if (nColumns < 0) { ResultSetMetaData rsmd = rs.getMetaData(); nColumns = rsmd.getColumnCount(); for (int i = 1; i <= nColumns; ++i) { String hdg = rsmd.getColumnLabel(i); headings.add(hdg);//from www . j a v a 2 s. c o m } } String[] values = new String[nColumns]; rows.add(values); for (int i = 1; i <= nColumns; ++i) { values[i - 1] = rs.getString(i); } } return nColumns; }
From source file:uk.org.rbc1b.roms.controller.report.ReportsController.java
private ReportResults extractResults(String sql) throws SQLException { Connection con = DataSourceUtils.getConnection(dataSource); Statement s = con.createStatement(); ResultSet rs = s.executeQuery(sql); ReportResults reportResults = new ReportResults(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); List<Integer> columnTypeIds = new ArrayList<Integer>(); for (int i = 0; i < columnCount; i++) { columnTypeIds.add(rsmd.getColumnType(i + 1)); }// www.j a va 2 s . c o m reportResults.columnNames = new ArrayList<String>(); for (int i = 0; i < columnCount; i++) { reportResults.columnNames.add(rsmd.getColumnLabel(i + 1)); } reportResults.resultRows = new ArrayList<List<String>>(); while (rs.next()) { List<String> resultRow = new ArrayList<String>(); for (int i = 0; i < columnCount; i++) { Integer columnTypeId = columnTypeIds.get(i); if (columnTypeId.intValue() == Types.BOOLEAN || columnTypeId.intValue() == Types.BIT) { resultRow.add(Boolean.valueOf(rs.getBoolean(i + 1)).toString()); } else { resultRow.add(rs.getString(i + 1)); } } reportResults.resultRows.add(resultRow); } return reportResults; }
From source file:servlet.CustomerControl.java
protected void doListTickets(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); JSONObject jso0 = new JSONObject(); JSONArray jsa0 = new JSONArray(); try {/*from w w w .j av a 2s . com*/ jso0.put("tickets", jsa0); } catch (JSONException ex) { Logger.getLogger(CustomerControl.class.getName()).log(Level.SEVERE, null, ex); } User user = (User) session.getAttribute("user"); int userID; int userCredit = 0; int userLP = 0; if (user != null) { userID = user.getUserID(); userCredit = user.getCredit(); userLP = user.getTradePoint(); } else { out.println(jso0.toString()); return; } ServletContext sc = getServletContext(); String db_driver = sc.getInitParameter("db_driver"), db_url = sc.getInitParameter("db_url"), db_user = sc.getInitParameter("db_user"), db_password = sc.getInitParameter("db_password"), db_q_tickets = "SELECT DISTINCT t.ticketID, t.state, s.rowName, s.seatName," + " (ms.price + s.surcharge) AS 'price', ms.playtime, m.*, h.houseName," + " c.cinemaName, c.cinemaDistrict, c.cinemaAddress, c.tel, c.image1" + " FROM Ticket t, MovieSession ms, Movie m, Seat s, House h, Cinema c" + " WHERE t.msID = ms.msID" + " AND ms.houseID = h.houseID" + " AND h.cinemaID = c.cinemaID" + " AND h.houseID = s.houseID" + " AND t.seatID = s.seatID" + " AND ms.movieID = m.movieID" + " AND t.userID = ?;"; try { Class.forName(db_driver); Connection conn = DriverManager.getConnection(db_url, db_user, db_password); PreparedStatement statmt = conn.prepareStatement(db_q_tickets); statmt.setInt(1, userID); if (statmt.execute()) { ResultSet rs = statmt.getResultSet(); ResultSetMetaData rsmd = rs.getMetaData(); int numOfColumns = rsmd.getColumnCount(); while (rs.next()) { JSONObject jso1 = new JSONObject(); jsa0.put(jso1); for (int i = 1; i <= numOfColumns; i++) { jso1.put(rsmd.getColumnLabel(i), rs.getString(i)); } String playtime = jso1.getString("playtime"); jso1.put("date", playtime.substring(0, 10)); jso1.put("time", playtime.subSequence(11, 16)); } } conn.close(); out.println(jso0.toString()); } catch (ClassNotFoundException ex) { Logger.getLogger(CustomerControl.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(CustomerControl.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { Logger.getLogger(CustomerControl.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.onion.ezorm.executor.AbstractJdbcSqlExecutor.java
@Override public <T> List<T> list(SQL sql, ObjectWrapper<T> wrapper) throws SQLException { if (sql instanceof EmptySQL) return new ArrayList<>(); //sql??sql//from ww w . j a va 2 s.c om SQLInfo info = compileSql(sql); printSql(info);//?sql? Connection connection = getConnection(); //SQL PreparedStatement statement = connection.prepareStatement(info.getSql()); this.preparedParam(statement, info); //sql ResultSet resultSet = statement.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int count = metaData.getColumnCount(); //?sql?? List<String> headers = new ArrayList<>(); for (int i = 1; i <= count; i++) { headers.add(metaData.getColumnLabel(i)); } wrapper.setUp(headers); int index = 0; List<T> datas = new ArrayList<>(); while (resultSet.next()) { //, T data = wrapper.newInstance(); for (int i = 0; i < headers.size(); i++) { Object value = resultSet.getObject(i + 1); wrapper.wrapper(data, index, headers.get(i), value); } // for (String header : headers) { // Object value = resultSet.getObject(header); // wrapper.wrapper(data, index, header, value); // } index++; wrapper.done(data); datas.add(data); } closeResultSet(resultSet); closeStatement(statement); //?JDBC releaseConnection(connection); return datas; }
From source file:at.ac.tuwien.inso.subcat.reporter.Reporter.java
private void exportRows(ExporterConfig config, Project project, int commitDictId, int bugDictId, Settings settings, final ReportWriter formatter, String outputPath, Map<String, Object> vars) throws SQLException, Exception { formatter.init(project, settings, outputPath); model.rawForeach(config.getQuery(), vars, new ResultCallback() { @Override// w w w. j a v a2 s . co m public void processResult(ResultSet res) throws SemanticException, SQLException, Exception { ResultSetMetaData meta = res.getMetaData(); String[] titles = new String[meta.getColumnCount()]; for (int i = 0; i < titles.length; i++) { titles[i] = meta.getColumnLabel(i + 1); } formatter.writeHeader(titles); while (res.next()) { String[] data = new String[titles.length]; for (int i = 0; i < data.length; i++) { data[i] = res.getString(i + 1); } formatter.writeSet(data); } formatter.writeFooter(titles); } }); }
From source file:org.hyperic.hq.plugin.postgresql.TableIndexCollector.java
/** * in the first collect call we collet metrics for all tables and indexes (where* are enpty) * afert that we onlu collect metrics for configured tables and indexes (where* have values) *//*from w w w .java 2 s . c o m*/ @Override public void collect() { Properties p = getProperties(); String user = p.getProperty(PostgreSQL.PROP_USER); String pass = p.getProperty(PostgreSQL.PROP_PASS); String db = p.getProperty(PostgreSQL.PROP_DB); String queryTable = "SELECT * FROM pg_stat_user_tables " + whereTable; String queryIndex = "SELECT * FROM pg_stat_user_indexes " + whereIndex; Connection conn = null; try { String url = PostgreSQL.prepareUrl(p, db); log.debug("[collect] url:'" + url + "'"); conn = DriverManager.getConnection(url, user, pass); // TABLES if (firstCollect || (tables.size() > 0)) { log.debug("[collect] queryTable='" + queryTable + "'"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(queryTable); ResultSetMetaData md = rs.getMetaData(); while (rs.next()) { String tableName = rs.getString("relname"); String schemaName = rs.getString("schemaname"); setValue("table." + schemaName + "." + tableName + "." + Metric.ATTR_AVAIL, Metric.AVAIL_UP); for (int c = 1; c <= md.getColumnCount(); c++) { setValue("table." + schemaName + "." + tableName + "." + md.getColumnLabel(c), rs.getString(c)); } } DBUtil.closeJDBCObjects(log, null, stmt, rs); } // INDXES if (firstCollect || (indexes.size() > 0)) { log.debug("[collect] queryInex='" + queryIndex + "'"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(queryIndex); ResultSetMetaData md = rs.getMetaData(); while (rs.next()) { String indexrelName = rs.getString("indexrelname"); String schemaName = rs.getString("schemaname"); setValue("index." + schemaName + "." + indexrelName + "." + Metric.ATTR_AVAIL, Metric.AVAIL_UP); for (int c = 1; c <= md.getColumnCount(); c++) { setValue("index." + schemaName + "." + indexrelName + "." + md.getColumnLabel(c), rs.getString(c)); } } } } catch (Exception e) { final String msg = "Error getting metrics: " + e.getMessage(); setErrorMessage(msg, e); log.debug("[collect] " + msg, e); } finally { DBUtil.closeJDBCObjects(log, conn, null, null); } firstCollect = false; }
From source file:moe.yuna.palinuridae.core.BaseDao.java
public List<Map<String, Object>> select(final Selector selector) throws DBUtilException { return getJdbcTemplate().query(getDialect().select(selector), (stat) -> { for (int i = 0; i < selector.getValues().size(); i++) { stat.setObject(i + 1, selector.getValues().get(i)); }// w w w . j ava 2 s . c o m }, (DBCallable<List<Map<String, Object>>>) (rs) -> { ResultSetMetaData md = rs.getMetaData(); List<Map<String, Object>> rlist = new ArrayList<>(); while (rs.next()) { Map<String, Object> map = new HashMap<String, Object>(); for (int i = 1; i <= md.getColumnCount(); i++) { // map.put(md.getColumnName(i), rs.getObject(i)); map.put(md.getColumnLabel(i), rs.getObject(i)); } rlist.add(map); } return rlist; }); }