List of usage examples for java.sql ResultSetMetaData getColumnCount
int getColumnCount() throws SQLException;
ResultSet
object. From source file:com.quest.orahive.HiveJdbcClient.java
private static List<OracleTableColumn> getOracleTableColumnsForHiveResults(ResultSet resultSet) { List<OracleTableColumn> result = null; try {/* ww w . j av a 2 s.c o m*/ ResultSetMetaData metaData = resultSet.getMetaData(); result = new ArrayList<OracleTableColumn>(metaData.getColumnCount()); for (int idx = 0; idx < metaData.getColumnCount(); idx++) { OracleTableColumn column = new OracleTableColumn(); result.add(column); // column Name... column.setName(metaData.getColumnLabel(idx + 1)); //<- 1-based in JDBC; // Sql Type... column.sqlType = metaData.getColumnType(idx + 1); //<- 1-based in JDBC // column Oracle data-type... Constants.OracleType oracleType = javaSqlTypeToOracleType(column.sqlType); switch (oracleType) { case VARCHAR2: { column.oracleDataType = String.format("%s(%d)", oracleType.toString(), 4000 // Max length for a varchar ); break; } default: { column.oracleDataType = oracleType.toString(); break; } } } } catch (SQLException ex) { LOG.error("An error occurred when processing the metadata for the Hive result-set.", ex); System.exit(1); } return result; }
From source file:com.healthmarketscience.jackcess.ImportUtil.java
/** * Copy an existing JDBC ResultSet into a new (or optionally existing) table * in this database.// w w w .ja v a 2s . c o m * * @param name Name of the new table to create * @param source ResultSet to copy from * @param filter valid import filter * @param useExistingTable if {@code true} use current table if it already * exists, otherwise, create new table with unique * name * * @return the name of the imported table * * @see Builder */ public static String importResultSet(ResultSet source, Database db, String name, ImportFilter filter, boolean useExistingTable) throws SQLException, IOException { ResultSetMetaData md = source.getMetaData(); name = Database.escapeIdentifier(name); Table table = null; if (!useExistingTable || ((table = db.getTable(name)) == null)) { List<Column> columns = new LinkedList<Column>(); for (int i = 1; i <= md.getColumnCount(); i++) { Column column = new Column(); column.setName(Database.escapeIdentifier(md.getColumnName(i))); int lengthInUnits = md.getColumnDisplaySize(i); column.setSQLType(md.getColumnType(i), lengthInUnits); DataType type = column.getType(); // we check for isTrueVariableLength here to avoid setting the length // for a NUMERIC column, which pretends to be var-len, even though it // isn't if (type.isTrueVariableLength() && !type.isLongValue()) { column.setLengthInUnits((short) lengthInUnits); } if (type.getHasScalePrecision()) { int scale = md.getScale(i); int precision = md.getPrecision(i); if (type.isValidScale(scale)) { column.setScale((byte) scale); } if (type.isValidPrecision(precision)) { column.setPrecision((byte) precision); } } columns.add(column); } table = createUniqueTable(db, name, columns, md, filter); } List<Object[]> rows = new ArrayList<Object[]>(COPY_TABLE_BATCH_SIZE); int numColumns = md.getColumnCount(); while (source.next()) { Object[] row = new Object[numColumns]; for (int i = 0; i < row.length; i++) { row[i] = source.getObject(i + 1); } row = filter.filterRow(row); if (row == null) { continue; } rows.add(row); if (rows.size() == COPY_TABLE_BATCH_SIZE) { table.addRows(rows); rows.clear(); } } if (rows.size() > 0) { table.addRows(rows); } return table.getName(); }
From source file:com.squid.kraken.v4.caching.redis.datastruct.RawMatrix.java
public static RawMatrix readExecutionItem(IExecutionItem item, long maxRecords) throws SQLException, ScopeException { long metter_start = System.currentTimeMillis(); try {// ww w . j a v a2 s . co m RawMatrix matrix = new RawMatrix(); ResultSet result = item.getResultSet(); IJDBCDataFormatter formatter = item.getDataFormatter(); // ResultSetMetaData metadata = result.getMetaData(); int nbColumns = metadata.getColumnCount(); IVendorSupport vendorSpecific; vendorSpecific = VendorSupportRegistry.INSTANCE.getVendorSupport(item.getDatabase()); int[] normalizedTypes = vendorSpecific.getVendorMetadataSupport().normalizeColumnType(result); int i = 0; while (i < nbColumns) { matrix.colTypes.add(normalizedTypes[i]); matrix.colNames.add(metadata.getColumnName(i + 1)); i++; } int count = 0; matrix.moreData = false; // while ((count++ < maxRecords || maxRecords < 0) && (matrix.moreData = result.next())) { Object[] rawrow = new Object[nbColumns]; i = 0; while (i < nbColumns) { Object value = result.getObject(i + 1); Object unbox = formatter.unboxJDBCObject(value, matrix.colTypes.get(i)); if (unbox instanceof String) { String stringVal = (String) unbox; rawrow[i] = DimensionValuesDictionary.INSTANCE.getRef(stringVal); } else { rawrow[i] = unbox; } i++; } matrix.addRow(new RawRow(rawrow)); count++; } long metter_finish = new Date().getTime(); if (logger.isDebugEnabled()) { logger.debug(("SQLQuery#" + item.getID() + "read " + (count - 1) + " row(s) in " + (metter_finish - metter_start) + " ms.")); } return matrix; } finally { item.close(); } }
From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java
/** * query to csv/* w w w . j av a 2 s. co m*/ * * @param userDB * @param strQuery * @param listParam * @param isAddHead is true add head title * @param strDelimiter if delimite is null default comma(,) */ @SuppressWarnings("deprecation") public static String selectToCSV(final UserDBDAO userDB, final String strQuery, final List<Object> listParam, final boolean isAddHead, final String strDelimiter) throws Exception { final StringWriter stWriter = new StringWriter(); SqlMapClient client = TadpoleSQLManager.getInstance(userDB); QueryRunner qr = new QueryRunner(client.getDataSource()); qr.query(strQuery, listParam.toArray(), new ResultSetHandler<Object>() { @Override public Object handle(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); char strDel; if ("".equals(strDelimiter)) { strDel = ','; } else if (StringUtils.equalsIgnoreCase("\t", strDelimiter)) { strDel = (char) 9; } else { strDel = strDelimiter.charAt(0); } CSVWriter csvWriter = new CSVWriter(stWriter, strDel); if (isAddHead) { String[] arryString = new String[metaData.getColumnCount()]; for (int i = 1; i <= metaData.getColumnCount(); i++) { arryString[i - 1] = metaData.getColumnLabel(i); } csvWriter.writeNext(arryString); } while (rs.next()) { String[] arryString = new String[metaData.getColumnCount()]; for (int i = 1; i <= metaData.getColumnCount(); i++) { arryString[i - 1] = rs.getString(i); } csvWriter.writeNext(arryString); } return stWriter.toString(); } }); return stWriter.toString(); }
From source file:com.manydesigns.portofino.persistence.QueryUtils.java
/** * Runs a SQL query against a session. The query can contain placeholders for the parameters, as supported by * {@link PreparedStatement}./*from w w w . j a v a 2 s .c o m*/ * * @param session the session * @param queryString the query * @param parameters parameters to substitute in the query * @return the results of the query as an Object[] (an array cell per column) */ public static List<Object[]> runSql(Session session, final String queryString, final Object[] parameters) { final List<Object[]> result = new ArrayList<Object[]>(); try { session.doWork(new Work() { public void execute(Connection connection) throws SQLException { PreparedStatement stmt = connection.prepareStatement(queryString); ResultSet rs = null; try { for (int i = 0; i < parameters.length; i++) { stmt.setObject(i + 1, parameters[i]); } rs = stmt.executeQuery(); ResultSetMetaData md = rs.getMetaData(); int cc = md.getColumnCount(); while (rs.next()) { Object[] current = new Object[cc]; for (int i = 0; i < cc; i++) { current[i] = rs.getObject(i + 1); } result.add(current); } } finally { if (null != rs) { rs.close(); } if (null != stmt) { stmt.close(); } } } }); } catch (HibernateException e) { session.getTransaction().rollback(); session.beginTransaction(); throw e; } return result; }
From source file:com.manydesigns.portofino.persistence.QueryUtils.java
/** * Runs a SQL query against a session. The query can contain placeholders for the parameters, as supported by * {@link PreparedStatement}./*w ww . j ava 2 s.c om*/ * * @param session the session * @param queryString the query * @param parameters parameters to substitute in the query * @return the results of the query as an Object[] (an array cell per column) */ // hongliangpan add public static List<Map<String, Object>> runSqlReturnMap(Session session, final String queryString, final Object[] parameters) { final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); try { session.doWork(new Work() { public void execute(Connection connection) throws SQLException { PreparedStatement stmt = connection.prepareStatement(queryString); ResultSet rs = null; try { for (int i = 0; i < parameters.length; i++) { stmt.setObject(i + 1, parameters[i]); } rs = stmt.executeQuery(); ResultSetMetaData md = rs.getMetaData(); int cc = md.getColumnCount(); while (rs.next()) { Map<String, Object> t_row = new LinkedHashMap<String, Object>(); for (int i = 0; i < cc; i++) { Object t_value = rs.getObject(i + 1); t_row.put(md.getColumnLabel(i + 1), t_value); } result.add(t_row); } } finally { if (null != rs) { rs.close(); } if (null != stmt) { stmt.close(); } } } }); } catch (HibernateException e) { session.getTransaction().rollback(); session.beginTransaction(); throw e; } return result; }
From source file:MainClass.java
public MainClass() { try {/*from www .j av a 2 s . c o m*/ Class.forName("COM.cloudscape.core.RmiJdbcDriver"); Connection connection = DriverManager.getConnection("jdbc:cloudscape:rmi:books"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM authors"); ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); for (int i = 1; i <= numberOfColumns; i++) { System.out.println(metaData.getColumnName(i) + "\t"); } while (resultSet.next()) { for (int i = 1; i <= numberOfColumns; i++) { System.out.println(resultSet.getObject(i) + "\t"); } System.out.println("\n"); } statement.close(); connection.close(); } catch (SQLException sqlException) { System.out.println(sqlException.getMessage()); } catch (ClassNotFoundException classNotFound) { System.out.println("Driver Not Found"); System.exit(1); } }
From source file:com.healthmarketscience.jackcess.util.ImportUtil.java
/** * Copy an existing JDBC ResultSet into a new (or optionally existing) table * in this database.// w w w.j a va 2s . co m * * @param name Name of the new table to create * @param source ResultSet to copy from * @param filter valid import filter * @param useExistingTable if {@code true} use current table if it already * exists, otherwise, create new table with unique * name * * @return the name of the imported table * * @see Builder */ public static String importResultSet(ResultSet source, Database db, String name, ImportFilter filter, boolean useExistingTable) throws SQLException, IOException { ResultSetMetaData md = source.getMetaData(); name = TableBuilder.escapeIdentifier(name); Table table = null; if (!useExistingTable || ((table = db.getTable(name)) == null)) { List<ColumnBuilder> columns = toColumns(md); table = createUniqueTable(db, name, columns, md, filter); } List<Object[]> rows = new ArrayList<Object[]>(COPY_TABLE_BATCH_SIZE); int numColumns = md.getColumnCount(); while (source.next()) { Object[] row = new Object[numColumns]; for (int i = 0; i < row.length; i++) { row[i] = source.getObject(i + 1); } row = filter.filterRow(row); if (row == null) { continue; } rows.add(row); if (rows.size() == COPY_TABLE_BATCH_SIZE) { table.addRows(rows); rows.clear(); } } if (rows.size() > 0) { table.addRows(rows); } return table.getName(); }
From source file:shell.framework.dao.support.ListExtractor4Map.java
public Object extractData(ResultSet rs) throws SQLException, DataAccessException { ResultSetMetaData rsmd = rs.getMetaData(); int columnNum = rsmd.getColumnCount(); List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); while (rs.next()) { Map<String, Object> map4Row = new HashMap<String, Object>(); for (int i = 1; i <= columnNum; i++) { map4Row.put(rsmd.getColumnName(i), rs.getObject(i)); }// w w w . ja v a2 s .co m result.add(map4Row); } return result; }
From source file:com.qualogy.qafe.business.integration.rdb.MetaDataRowMapper.java
/** * Method for mapping rows inherited from RowMapper. * Method maps rows to a Map using columnname. */// w w w . ja v a2 s. c o m public Object mapRow(ResultSet rs, int rowNum) throws SQLException { // Map<String, Object> output = new CaseInsensitiveMap(); Map<String, Object> output = new DataMap(); ResultSetMetaData md = rs.getMetaData(); for (int i = 1; i <= md.getColumnCount(); i++) { output.put(md.getColumnName(i), rs.getObject(i)); } return output; }