List of usage examples for java.sql ResultSetMetaData getColumnName
String getColumnName(int column) throws SQLException;
From source file:at.alladin.rmbt.statisticServer.StatisticsResource.java
private static void fillJSON(final String lang, final ResultSet rs, final JSONArray providers) throws SQLException, JSONException { final ResultSetMetaData metaData = rs.getMetaData(); final int columnCount = metaData.getColumnCount(); while (rs.next()) { final JSONObject obj = new JSONObject(); for (int j = 1; j <= columnCount; j++) { final String colName = metaData.getColumnName(j); Object data = rs.getObject(j); if (colName.equals("name") && data == null) if (lang != null && lang.equals("de")) data = "Andere Betreiber"; else data = "Other operators"; if (colName.equals("shortname") && data == null) { if (lang != null && lang.equals("de")) data = "Andere"; else data = "Others"; }//from ww w . j a v a2 s . c om obj.put(colName, data); } providers.put(obj); } }
From source file:org.diffkit.util.DKSqlUtil.java
public static String[] getColumnNames(ResultSet resultSet_) throws SQLException { if (resultSet_ == null) return null; ResultSetMetaData metaData = resultSet_.getMetaData(); int columnCount = metaData.getColumnCount(); if (columnCount < 1) return null; String[] columnNames = new String[columnCount]; for (int i = 1; i <= columnCount; i++) { columnNames[i - 1] = metaData.getColumnName(i); }/*from w w w .j av a 2 s.c o m*/ return columnNames; }
From source file:com.streamsets.pipeline.stage.BaseHiveIT.java
/** * Validate structure of the result set (column names and types). *//* w w w.j a va 2 s . c o m*/ public static void assertResultSetStructure(ResultSet rs, Pair<String, Integer>... columns) throws Exception { ResultSetMetaData metaData = rs.getMetaData(); Assert.assertEquals(Utils.format("Unexpected number of columns"), columns.length, metaData.getColumnCount()); int i = 1; for (Pair<String, Integer> column : columns) { Assert.assertEquals(Utils.format("Unexpected name for column {}", i), column.getLeft(), metaData.getColumnName(i)); Assert.assertEquals(Utils.format("Unexpected type for column {}", i), (int) column.getRight(), metaData.getColumnType(i)); i++; } }
From source file:com.viettel.ws.client.JDBCUtil.java
/** * Create document using DOM api//w ww. j a v a2s . c o m * * @param rs a result set * @param doc a input document for append content * @param rsName name of the appended element * @return a document after append content * @throws ParserConfigurationException If error when parse XML string * @throws SQLException If error when read data from database */ public static Document add2Document1(ResultSet rs1, ResultSet rs2, Document doc, String rsName) throws ParserConfigurationException, SQLException { if (rs1 == null && rs2 == null) { return doc; } //Get root element Element root = doc.getDocumentElement(); Element rsElement = doc.createElement(rsName); root.appendChild(rsElement); if (rs1 != null) { ResultSetMetaData rsmd = rs1.getMetaData(); int colCount = rsmd.getColumnCount(); while (rs1.next()) { Element row = doc.createElement("Row"); rsElement.appendChild(row); try { for (int i = 1; i <= colCount; i++) { String columnName = rsmd.getColumnName(i); Object value = rs1.getObject(i); if (value == null) { value = ""; } Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 // logger.error(e, e); } } } if (rs2 != null) { ResultSetMetaData rsmd = rs2.getMetaData(); int colCount = rsmd.getColumnCount(); while (rs2.next()) { Element row = doc.createElement("Row"); rsElement.appendChild(row); try { for (int i = 1; i <= colCount; i++) { String columnName = rsmd.getColumnName(i); Object value = rs2.getObject(i); if (value == null) { value = ""; } Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 // logger.error(e, e); } } } return doc; }
From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java
/** * query to xml/* w w w . j ava2s .c o m*/ * * @param userDB * @param strQuery * @param listParam */ @SuppressWarnings("deprecation") public static String selectToXML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam) throws Exception { final StringWriter stWriter = new StringWriter(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement("Results"); doc.appendChild(results); 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(); while (rs.next()) { Element row = doc.createElement("Row"); results.appendChild(row); for (int i = 1; i <= metaData.getColumnCount(); i++) { String columnName = metaData.getColumnName(i); Object value = rs.getObject(i) == null ? "" : rs.getObject(i); Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } return stWriter.toString(); } }); DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 4); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1"); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); return stWriter.toString(); }
From source file:br.bookmark.db.util.ResultSetUtils.java
/** * Returns next record of result set as a Map. * The keys of the map are the column names, * as returned by the metadata.//from w w w. ja v a2 s. c o m * The values are the columns as Objects. * * @param resultSet The ResultSet to process. * @exception SQLException if an error occurs. */ public static Map getMap(ResultSet resultSet) throws SQLException { // Acquire resultSet MetaData ResultSetMetaData metaData = resultSet.getMetaData(); int cols = metaData.getColumnCount(); // Create hashmap, sized to number of columns HashMap row = new HashMap(cols, 1); // Transfer record into hashmap if (resultSet.next()) { for (int i = 1; i <= cols; i++) { row.put(metaData.getColumnName(i), resultSet.getObject(i)); } } // end while return ((Map) row); }
From source file:com.trackplus.ddl.DataReader.java
private static int getTableData(BufferedWriter writer, BufferedWriter writerClean, BufferedWriter writerUpdate, BufferedWriter writerUpdateClean, Connection con, String tableName, StringValueConverter stringValueConverter) throws DDLException { Statement st = MetaDataBL.createStatement(con); String sql = "SELECT * FROM " + tableName; ResultSet rs;/* w ww . jav a2s .co m*/ try { rs = st.executeQuery(sql); } catch (SQLException e) { throw new DDLException(e.getMessage(), e); } int idx = 0; int idxUpdate = 0; try { ResultSetMetaData md = rs.getMetaData(); String primaryKey = MetaDataBL.getPrimaryKey(tableName, con); int columnCount = md.getColumnCount(); StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO " + tableName + "("); for (int i = 0; i < columnCount; i++) { String columnName = md.getColumnName(i + 1); sb.append(columnName); if (i < columnCount - 1) { sb.append(", "); } } sb.append(") VALUES("); StringBuilder updateSQL; while (rs.next()) { StringBuilder line = new StringBuilder(); line.append(sb); String primaryKeyValue = rs.getString(primaryKey); for (int i = 0; i < columnCount; i++) { String value; String columnName = md.getColumnName(i + 1); try { value = stringValueConverter.getStringValue(md, i + 1, rs, tableName); } catch (DDLException ex) { LOGGER.warn("Error: " + ex.getMessage() + " for column:" + columnName + " in table:" + tableName + " primary key " + primaryKey + "=" + primaryKeyValue + ". Will be set to NULL!"); value = null; } if (value != null && value.length() > MAX_VALUE_STRING) { if ("MAILBODY".equalsIgnoreCase(columnName) || "CLOBVALUE".equalsIgnoreCase(columnName)) { //blob } else { updateSQL = new StringBuilder(); updateSQL.append("UPDATE ").append(tableName).append(" SET ").append(columnName) .append("="); updateSQL.append(value).append("\n WHERE ").append(primaryKey).append("=") .append(primaryKeyValue); updateSQL.append(";"); MetaDataBL.appendLine(writerUpdateClean, updateSQL.toString()); updateSQL.append(LINE_SEPARATOR); MetaDataBL.appendLine(writerUpdate, updateSQL.toString()); idxUpdate++; value = null; } } line.append(value); if (i < columnCount - 1) { line.append(", "); } } line.append(");"); MetaDataBL.appendLine(writerClean, line.toString()); line.append(LINE_SEPARATOR); MetaDataBL.appendLine(writer, line.toString()); idx++; } } catch (SQLException e) { throw new DDLException(e.getMessage(), e); } try { rs.close(); } catch (SQLException e) { throw new DDLException(e.getMessage(), e); } if (idxUpdate > 0) { LOGGER.warn("There was " + idxUpdate + " records with String size>" + MAX_VALUE_STRING + " found in table:" + tableName); } return idx; }
From source file:com.healthmarketscience.jackcess.util.ImportUtil.java
/** * Returns a List of Column instances converted from the given * ResultSetMetaData (this is the same method used by the various {@code * importResultSet()} methods)./* ww w.j ava2 s .c om*/ * * @return a List of Columns */ public static List<ColumnBuilder> toColumns(ResultSetMetaData md) throws SQLException { List<ColumnBuilder> columns = new LinkedList<ColumnBuilder>(); for (int i = 1; i <= md.getColumnCount(); i++) { ColumnBuilder column = new ColumnBuilder(md.getColumnName(i)).escapeName(); 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); } return columns; }
From source file:org.apache.nifi.util.hive.HiveJdbcCommon.java
public static long convertToCsvStream(final ResultSet rs, final OutputStream outStream, String recordName, ResultSetRowCallback callback, CsvOutputOptions outputOptions) throws SQLException, IOException { final ResultSetMetaData meta = rs.getMetaData(); final int nrOfColumns = meta.getColumnCount(); List<String> columnNames = new ArrayList<>(nrOfColumns); if (outputOptions.isHeader()) { if (outputOptions.getAltHeader() == null) { for (int i = 1; i <= nrOfColumns; i++) { String columnNameFromMeta = meta.getColumnName(i); // Hive returns table.column for column name. Grab the column name as the string after the last period int columnNameDelimiter = columnNameFromMeta.lastIndexOf("."); columnNames.add(columnNameFromMeta.substring(columnNameDelimiter + 1)); }/*from w w w . j a va 2s.c om*/ } else { String[] altHeaderNames = outputOptions.getAltHeader().split(","); columnNames = Arrays.asList(altHeaderNames); } } // Write column names as header row outStream.write( StringUtils.join(columnNames, outputOptions.getDelimiter()).getBytes(StandardCharsets.UTF_8)); if (outputOptions.isHeader()) { outStream.write("\n".getBytes(StandardCharsets.UTF_8)); } // Iterate over the rows long nrOfRows = 0; while (rs.next()) { if (callback != null) { callback.processRow(rs); } List<String> rowValues = new ArrayList<>(nrOfColumns); for (int i = 1; i <= nrOfColumns; i++) { final int javaSqlType = meta.getColumnType(i); final Object value = rs.getObject(i); switch (javaSqlType) { case CHAR: case LONGNVARCHAR: case LONGVARCHAR: case NCHAR: case NVARCHAR: case VARCHAR: String valueString = rs.getString(i); if (valueString != null) { // Removed extra quotes as those are a part of the escapeCsv when required. StringBuilder sb = new StringBuilder(); if (outputOptions.isQuote()) { sb.append("\""); if (outputOptions.isEscape()) { sb.append(StringEscapeUtils.escapeCsv(valueString)); } else { sb.append(valueString); } sb.append("\""); rowValues.add(sb.toString()); } else { if (outputOptions.isEscape()) { rowValues.add(StringEscapeUtils.escapeCsv(valueString)); } else { rowValues.add(valueString); } } } else { rowValues.add(""); } break; case ARRAY: case STRUCT: case JAVA_OBJECT: String complexValueString = rs.getString(i); if (complexValueString != null) { rowValues.add(StringEscapeUtils.escapeCsv(complexValueString)); } else { rowValues.add(""); } break; default: if (value != null) { rowValues.add(value.toString()); } else { rowValues.add(""); } } } // Write row values outStream.write( StringUtils.join(rowValues, outputOptions.getDelimiter()).getBytes(StandardCharsets.UTF_8)); outStream.write("\n".getBytes(StandardCharsets.UTF_8)); nrOfRows++; } return nrOfRows; }
From source file:gov.nih.nci.ncicb.cadsr.bulkloader.util.excel.DBExcelUtility.java
public static void displayResultSetRow(ResultSet rs) throws Exception { int maxcol = 20; StringBuffer sb = new StringBuffer(); ResultSetMetaData mdata = rs.getMetaData(); sb.append("\n"); maxcol = mdata.getColumnCount();//from w w w .j a v a2 s . c o m for (int i = 1; i <= maxcol; i++) { sb.append(mdata.getColumnName(i) + "\t"); } int rowcount = 0; sb.append("\n"); for (int i = 1; i <= maxcol; i++) { try { sb.append(rs.getObject(i) + "\t"); } catch (Exception e) { System.out.println("Exception " + e); } } System.out.println(sb.toString()); }