List of usage examples for java.sql ResultSetMetaData getColumnType
int getColumnType(int column) throws SQLException;
From source file:org.alinous.plugin.derby.DerbyDataSource.java
private List<Record> executeSelectSQL(Object connectionHandle, String sql, LimitOffsetClause limit, PostContext context, VariableRepository provider, AdjustWhere adjWhere, TypeHelper helper) throws DataSourceException, ExecutionException { Connection con = (Connection) connectionHandle; Statement stmt = null;//from www . j av a 2 s . c o m List<Record> retList = new LinkedList<Record>(); try { stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.execute(sql); ResultSet rs = stmt.getResultSet(); ResultSetMetaData metaData = rs.getMetaData(); if (limit != null && limit.isReady(context, provider, adjWhere)) { fetchWithOffset(rs, metaData, retList, limit, context, provider, adjWhere, helper); } else { while (rs.next()) { int cnt = metaData.getColumnCount(); Record rec = new Record(); for (int i = 0; i < cnt; i++) { String colName = metaData.getColumnName(i + 1).toUpperCase(); String value = rs.getString(i + 1); int colType = metaData.getColumnType(i + 1); rec.addFieldValue(colName, value, colType); } retList.add(rec); } } } catch (SQLException e) { throw new DataSourceException(e); } finally { try { stmt.close(); } catch (SQLException ignore) { } } return retList; }
From source file:org.siphon.jssql.SqlExecutor.java
/*** * ??/*w ww . j av a 2s . c o m*/ * @param connection * @param sql * @param args * @param travele function(columns, row) , return true , return false * @return * @throws SqlExecutorException */ public void travel(Connection connection, String sql, NativeArray args, ScriptFunction traveler) throws SqlExecutorException { if (connection == null) { this.travel(sql, args, traveler); return; } long start = System.currentTimeMillis(); PreparedStatement ps = null; ResultSet rs = null; boolean errorOccu = false; try { // logger.debug("execute travel " + sql + " with args: " + // JSON.tryStringify(args)); ps = connection.prepareStatement(sql); setArgs(ps, args); rs = ps.executeQuery(); ResultSetMetaData rsm = rs.getMetaData(); ScriptObjectMirror columns = columnListToNativeArray(rsm); while (rs.next()) { ScriptObjectMirror item = jsTypeUtil.newObject(); for (int i = 1; i <= rsm.getColumnCount(); i++) { String cname = this.useColumnLabelAsName ? rsm.getColumnLabel(i) : rsm.getColumnName(i); String label = convertColumnName(cname); item.put(cname, fieldValueToNativeObject(rsm.getColumnType(i), rs, cname)); } Object result = NativeFunction.call(traveler, traveler, item.to(ScriptObject.class), columns); // traveler.callMember("call", traveler, item, columns); if (JsTypeUtil.isTrue(result)) { break; } } } catch (SQLException | UnsupportedDataTypeException | ScriptException | NoSuchMethodException e) { errorOccu = true; throw new SqlExecutorException( "error occurs when query " + sql + " with args : " + JSON.tryStringify(args), e); } finally { long exhaust = System.currentTimeMillis() - start; if (exhaust > 30000) { logger.warn(String.format("%s with args:%s exhaust %s", sql, args, exhaust)); } DbConnectionUtil.close(rs); DbConnectionUtil.close(ps); } }
From source file:org.siphon.jssql.SqlExecutor.java
private ScriptObjectMirror columnListToNativeArray(ResultSetMetaData rsm) throws SQLException, ScriptException { ScriptObjectMirror arr = jsTypeUtil.newArray(); NativeArray narr = arr.to(NativeArray.class); // JSON.stringify(arr) for (int i = 1; i <= rsm.getColumnCount(); i++) { ScriptObjectMirror obj = jsTypeUtil.newObject(); String cname = this.useColumnLabelAsName ? rsm.getColumnLabel(i) : rsm.getColumnName(i); String label = convertColumnName(cname); obj.put("name", label); obj.put("type", translateTypeName(rsm.getColumnType(i), rsm.getColumnTypeName(i))); // NativeArray.pushObject(narr, obj.to(ScriptObject.class)); arr.callMember("push", obj); }/*from ww w. j ava 2s .c om*/ return arr; }
From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java
public Field resultToField(ResultSetMetaData md, ResultSet rs, int columnIndex, int maxClobSize, int maxBlobSize, DataType userSpecifiedType, UnknownTypeAction unknownTypeAction, boolean timestampToString) throws SQLException, IOException, StageException { Field field;/*from ww w .ja v a 2 s. com*/ if (userSpecifiedType != DataType.USE_COLUMN_TYPE) { // If user specifies the data type, overwrite the column type returned by database. field = Field.create(Field.Type.valueOf(userSpecifiedType.getLabel()), rs.getObject(columnIndex)); } else { // All types as of JDBC 2.0 are here: // https://docs.oracle.com/javase/8/docs/api/constant-values.html#java.sql.Types.ARRAY // Good source of recommended mappings is here: // http://www.cs.mun.ca/java-api-1.5/guide/jdbc/getstart/mapping.html switch (md.getColumnType(columnIndex)) { case Types.BIGINT: field = Field.create(Field.Type.LONG, rs.getObject(columnIndex)); break; case Types.BINARY: case Types.LONGVARBINARY: case Types.VARBINARY: field = Field.create(Field.Type.BYTE_ARRAY, rs.getBytes(columnIndex)); break; case Types.BIT: case Types.BOOLEAN: field = Field.create(Field.Type.BOOLEAN, rs.getObject(columnIndex)); break; case Types.CHAR: case Types.LONGNVARCHAR: case Types.LONGVARCHAR: case Types.NCHAR: case Types.NVARCHAR: case Types.VARCHAR: field = Field.create(Field.Type.STRING, rs.getObject(columnIndex)); break; case Types.CLOB: case Types.NCLOB: field = Field.create(Field.Type.STRING, getClobString(rs.getClob(columnIndex), maxClobSize)); break; case Types.BLOB: field = Field.create(Field.Type.BYTE_ARRAY, getBlobBytes(rs.getBlob(columnIndex), maxBlobSize)); break; case Types.DATE: field = Field.create(Field.Type.DATE, rs.getDate(columnIndex)); break; case Types.DECIMAL: case Types.NUMERIC: field = Field.create(Field.Type.DECIMAL, rs.getBigDecimal(columnIndex)); field.setAttribute(HeaderAttributeConstants.ATTR_SCALE, String.valueOf(rs.getMetaData().getScale(columnIndex))); field.setAttribute(HeaderAttributeConstants.ATTR_PRECISION, String.valueOf(rs.getMetaData().getPrecision(columnIndex))); break; case Types.DOUBLE: field = Field.create(Field.Type.DOUBLE, rs.getObject(columnIndex)); break; case Types.FLOAT: case Types.REAL: field = Field.create(Field.Type.FLOAT, rs.getObject(columnIndex)); break; case Types.INTEGER: field = Field.create(Field.Type.INTEGER, rs.getObject(columnIndex)); break; case Types.ROWID: field = Field.create(Field.Type.STRING, rs.getRowId(columnIndex).toString()); break; case Types.SMALLINT: case Types.TINYINT: field = Field.create(Field.Type.SHORT, rs.getObject(columnIndex)); break; case Types.TIME: field = Field.create(Field.Type.TIME, rs.getObject(columnIndex)); break; case Types.TIMESTAMP: final Timestamp timestamp = rs.getTimestamp(columnIndex); if (timestampToString) { field = Field.create(Field.Type.STRING, timestamp == null ? null : timestamp.toString()); } else { field = Field.create(Field.Type.DATETIME, timestamp); if (timestamp != null) { final long actualNanos = timestamp.getNanos() % NANOS_TO_MILLIS_ADJUSTMENT; if (actualNanos > 0) { field.setAttribute(FIELD_ATTRIBUTE_NANOSECONDS, String.valueOf(actualNanos)); } } } break; // Ugly hack until we can support LocalTime, LocalDate, LocalDateTime, etc. case Types.TIME_WITH_TIMEZONE: OffsetTime offsetTime = rs.getObject(columnIndex, OffsetTime.class); field = Field.create(Field.Type.TIME, Date.from(offsetTime.atDate(LocalDate.MIN).toInstant())); break; case Types.TIMESTAMP_WITH_TIMEZONE: OffsetDateTime offsetDateTime = rs.getObject(columnIndex, OffsetDateTime.class); field = Field.create(Field.Type.ZONED_DATETIME, offsetDateTime.toZonedDateTime()); break; //case Types.REF_CURSOR: // JDK8 only case Types.SQLXML: case Types.STRUCT: case Types.ARRAY: case Types.DATALINK: case Types.DISTINCT: case Types.JAVA_OBJECT: case Types.NULL: case Types.OTHER: case Types.REF: default: if (unknownTypeAction == null) { return null; } switch (unknownTypeAction) { case STOP_PIPELINE: throw new StageException(JdbcErrors.JDBC_37, md.getColumnType(columnIndex), md.getColumnLabel(columnIndex)); case CONVERT_TO_STRING: Object value = rs.getObject(columnIndex); if (value != null) { field = Field.create(Field.Type.STRING, rs.getObject(columnIndex).toString()); } else { field = Field.create(Field.Type.STRING, null); } break; default: throw new IllegalStateException("Unknown action: " + unknownTypeAction); } } } return field; }
From source file:com.glaf.core.jdbc.QueryHelper.java
@SuppressWarnings("unchecked") public List<ColumnDefinition> getColumnDefinitions(String systemName, String sql, Map<String, Object> params) { SqlExecutor sqlExecutor = DBUtils.replaceSQL(sql, params); Connection conn = null;// ww w .j a v a 2s. c om PreparedStatement psmt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; try { conn = DBConnectionFactory.getConnection(systemName); psmt = conn.prepareStatement(sqlExecutor.getSql()); if (sqlExecutor.getParameter() != null) { List<Object> values = (List<Object>) sqlExecutor.getParameter(); JdbcUtils.fillStatement(psmt, values); } rs = psmt.executeQuery(); rsmd = rs.getMetaData(); int count = rsmd.getColumnCount(); List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>(); for (int index = 1; index <= count; index++) { int sqlType = rsmd.getColumnType(index); ColumnDefinition column = new ColumnDefinition(); column.setIndex(index); column.setColumnName(rsmd.getColumnName(index)); column.setColumnLabel(rsmd.getColumnLabel(index)); column.setJavaType(FieldType.getJavaType(sqlType)); column.setPrecision(rsmd.getPrecision(index)); column.setScale(rsmd.getScale(index)); if (column.getScale() == 0 && sqlType == Types.NUMERIC) { column.setJavaType("Long"); } column.setName(StringTools.camelStyle(column.getColumnLabel().toLowerCase())); columns.add(column); } return columns; } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(psmt); JdbcUtils.close(conn); } }
From source file:org.ensembl.healthcheck.util.DBUtils.java
/** * Compare a particular column in two ResultSets. * // w w w . ja v a2s. c om * @param rs1 * The first ResultSet to compare. * @param rs2 * The second ResultSet to compare. * @param i * The index of the column to compare. * @return True if the type and value of the columns match. */ public static boolean compareColumns(ResultSet rs1, ResultSet rs2, int i, boolean warnNull) { try { ResultSetMetaData rsmd = rs1.getMetaData(); Connection con1 = rs1.getStatement().getConnection(); Connection con2 = rs2.getStatement().getConnection(); if (rs1.getObject(i) == null) { if (warnNull) { logger.fine("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i) + " in " + DBUtils.getShortDatabaseName(con1)); } return (rs2.getObject(i) == null); // true if both are null } if (rs2.getObject(i) == null) { if (warnNull) { logger.fine("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i) + " in " + DBUtils.getShortDatabaseName(con2)); } return (rs1.getObject(i) == null); // true if both are null } // Note deliberate early returns for performance reasons switch (rsmd.getColumnType(i)) { case Types.INTEGER: return rs1.getInt(i) == rs2.getInt(i); case Types.SMALLINT: return rs1.getInt(i) == rs2.getInt(i); case Types.TINYINT: return rs1.getInt(i) == rs2.getInt(i); case Types.VARCHAR: String s1 = rs1.getString(i); String s2 = rs2.getString(i); // ignore "AUTO_INCREMENT=" part in final part of table // definition s1 = s1.replaceAll("AUTO_INCREMENT=[0-9]+ ", ""); s2 = s2.replaceAll("AUTO_INCREMENT=[0-9]+ ", ""); return s1.equals(s2); case Types.FLOAT: return rs1.getFloat(i) == rs2.getFloat(i); case Types.DOUBLE: return rs1.getDouble(i) == rs2.getDouble(i); case Types.TIMESTAMP: return rs1.getTimestamp(i).equals(rs2.getTimestamp(i)); default: // treat everything else as a String (should deal with ENUM and // TEXT) if (rs1.getString(i) == null || rs2.getString(i) == null) { return true; // ???? } else { return rs1.getString(i).equals(rs2.getString(i)); } } // switch } catch (SQLException se) { throw new SqlUncheckedException("Could not compare two columns sets", se); } }
From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java
/** * Create a column group and confirm that the {@code ResultSetMetaData} works. *//*w w w . ja v a 2s.c om*/ @Test public void testResultSetMetaData() throws Exception { Statement stmt = con.createStatement(); // Create the target Column family String createCF = "CREATE COLUMNFAMILY t33 (k int PRIMARY KEY," + "c text " + ") ;"; stmt.execute(createCF); stmt.close(); con.close(); // open it up again to see the new CF con = DriverManager .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS)); // paraphrase of the snippet from the ISSUE #33 provided test PreparedStatement statement = con.prepareStatement("update t33 set c=? where k=123"); statement.setString(1, "mark"); statement.executeUpdate(); ResultSet result = statement.executeQuery("SELECT k, c FROM t33;"); ResultSetMetaData metadata = result.getMetaData(); int colCount = metadata.getColumnCount(); System.out.println("Test Issue #33"); DatabaseMetaData md = con.getMetaData(); System.out.println(); System.out.println("--------------"); System.out.println("Driver Version : " + md.getDriverVersion()); System.out.println("DB Version : " + md.getDatabaseProductVersion()); System.out.println("Catalog term : " + md.getCatalogTerm()); System.out.println("Catalog : " + con.getCatalog()); System.out.println("Schema term : " + md.getSchemaTerm()); System.out.println("--------------"); while (result.next()) { metadata = result.getMetaData(); colCount = metadata.getColumnCount(); assertEquals("Total column count should match schema for t33", 2, metadata.getColumnCount()); System.out.printf("(%d) ", result.getRow()); for (int i = 1; i <= colCount; i++) { System.out.print(showColumn(i, result) + " "); switch (i) { case 1: assertEquals("First Column: k", "k", metadata.getColumnName(1)); assertEquals("First Column Type: int", Types.INTEGER, metadata.getColumnType(1)); break; case 2: assertEquals("Second Column: c", "c", metadata.getColumnName(2)); assertEquals("Second Column Type: text", Types.NVARCHAR, metadata.getColumnType(2)); break; } } System.out.println(); } }
From source file:com.hangum.tadpole.engine.sql.util.resultset.ResultSetUtils.java
/** * column of type/*from ww w. j av a2s . c om*/ * * @param isShowRowNum ? ?? . * @param rsm * @return * @throws SQLException */ public static Map<Integer, Integer> getColumnType(boolean isShowRowNum, ResultSetMetaData rsm) throws SQLException { Map<Integer, Integer> mapColumnType = new HashMap<Integer, Integer>(); int intStartIndex = 0; if (isShowRowNum) { intStartIndex++; mapColumnType.put(0, java.sql.Types.INTEGER); } for (int i = 0; i < rsm.getColumnCount(); i++) { // logger.debug("\t ==[column start]================================ ColumnName : " + rsm.getColumnName(i+1)); // logger.debug("\tColumnLabel : " + rsm.getColumnLabel(i+1)); // logger.debug("\t AutoIncrement : " + rsm.isAutoIncrement(i+1)); // logger.debug("\t Nullable : " + rsm.isNullable(i+1)); // logger.debug("\t CaseSensitive : " + rsm.isCaseSensitive(i+1)); // logger.debug("\t Currency : " + rsm.isCurrency(i+1)); // // logger.debug("\t DefinitelyWritable : " + rsm.isDefinitelyWritable(i+1)); // logger.debug("\t ReadOnly : " + rsm.isReadOnly(i+1)); // logger.debug("\t Searchable : " + rsm.isSearchable(i+1)); // logger.debug("\t Signed : " + rsm.isSigned(i+1)); //// logger.debug("\t Currency : " + rsm.isWrapperFor(i+1)); // logger.debug("\t Writable : " + rsm.isWritable(i+1)); // // logger.debug("\t ColumnClassName : " + rsm.getColumnClassName(i+1)); // logger.debug("\t CatalogName : " + rsm.getCatalogName(i+1)); // logger.debug("\t ColumnDisplaySize : " + rsm.getColumnDisplaySize(i+1)); // logger.debug("\t ColumnType : " + rsm.getColumnType(i+1)); // logger.debug("\t ColumnTypeName : " + rsm.getColumnTypeName(i+1)); // // mysql json ? ? 1 ? , ?? pgsql? json ? ? 1111 . // - 2015.10.21 mysql 5.7 if (StringUtils.equalsIgnoreCase("json", rsm.getColumnTypeName(i + 1))) { mapColumnType.put(i + intStartIndex, 1111); } else { mapColumnType.put(i + intStartIndex, rsm.getColumnType(i + 1)); } // logger.debug("\t Column Label " + rsm.getColumnLabel(i+1) ); // logger.debug("\t Precision : " + rsm.getPrecision(i+1)); // logger.debug("\t Scale : " + rsm.getScale(i+1)); // logger.debug("\t SchemaName : " + rsm.getSchemaName(i+1)); // logger.debug("\t TableName : " + rsm.getTableName(i+1)); // logger.debug("\t ==[column end]================================ ColumnName : " + rsm.getColumnName(i+1)); } return mapColumnType; }
From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.ExtendedRowSetBuilder.java
public int build(Document doc, String id, ResultSet rs, Set<Integer> keyField, Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter) throws Exception { if (rs == null) { return 0; }//www . java 2s . com int rowCounter = 0; Element docRoot = doc.getDocumentElement(); ResultSetMetaData metadata = rs.getMetaData(); buildFormatterAndNamesArray(metadata, fieldNameToFormatter, fieldIdToFormatter); boolean noKey = ((keyField == null) || keyField.isEmpty()); boolean isKeyCol = false; boolean isNull = false; Element data = null; Element row = null; Element col = null; Text text = null; String textVal = null; String precKey = null; String colKey = null; Map<String, Element> keyCols = new TreeMap<String, Element>(); while (rs.next()) { if (rowCounter % 10 == 0) { ThreadUtils.checkInterrupted(getClass().getSimpleName(), name, logger); } row = parser.createElementNS(doc, AbstractDBO.ROW_NAME, NS); parser.setAttribute(row, AbstractDBO.ID_NAME, id); for (int j = 1; j <= metadata.getColumnCount(); j++) { FieldFormatter fF = fFormatters[j]; String colName = colNames[j]; isKeyCol = (!noKey && keyField.contains(new Integer(j))); isNull = false; col = parser.createElementNS(doc, colName, NS); if (isKeyCol) { parser.setAttribute(col, AbstractDBO.ID_NAME, String.valueOf(j)); } switch (metadata.getColumnType(j)) { case Types.DATE: case Types.TIME: case Types.TIMESTAMP: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIMESTAMP_TYPE); Timestamp dateVal = rs.getTimestamp(j); isNull = dateVal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT); textVal = ""; } else { if (fF != null) { parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getDateFormat()); textVal = fF.formatDate(dateVal); } else { parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT); textVal = dateFormatter.format(dateVal); } } } break; case Types.DOUBLE: case Types.FLOAT: case Types.REAL: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE); float numVal = rs.getFloat(j); parser.setAttribute(col, AbstractDBO.NULL_NAME, "false"); if (fF != null) { parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat()); parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator()); parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator()); textVal = fF.formatNumber(numVal); } else { parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat); parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator); parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator); textVal = numberFormatter.format(numVal); } } break; case Types.BIGINT: case Types.INTEGER: case Types.NUMERIC: case Types.SMALLINT: case Types.TINYINT: { BigDecimal bigdecimal = rs.getBigDecimal(j); isNull = bigdecimal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { if (metadata.getScale(j) > 0) { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE); } else { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE); } textVal = ""; } else { if (fF != null) { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE); parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat()); parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator()); parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator()); textVal = fF.formatNumber(bigdecimal); } else if (metadata.getScale(j) > 0) { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE); parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat); parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator); parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator); textVal = numberFormatter.format(bigdecimal); } else { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE); textVal = bigdecimal.toString(); } } } break; case Types.NCHAR: case Types.NVARCHAR: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NSTRING_TYPE); textVal = rs.getNString(j); isNull = textVal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } } break; case Types.CHAR: case Types.VARCHAR: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.STRING_TYPE); textVal = rs.getString(j); isNull = textVal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } } break; case Types.NCLOB: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_NSTRING_TYPE); NClob clob = rs.getNClob(j); isNull = clob == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } else { Reader is = clob.getCharacterStream(); StringWriter str = new StringWriter(); IOUtils.copy(is, str); is.close(); textVal = str.toString(); } } break; case Types.CLOB: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_STRING_TYPE); Clob clob = rs.getClob(j); isNull = clob == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } else { Reader is = clob.getCharacterStream(); StringWriter str = new StringWriter(); IOUtils.copy(is, str); is.close(); textVal = str.toString(); } } break; case Types.BLOB: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BASE64_TYPE); Blob blob = rs.getBlob(j); isNull = blob == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } else { InputStream is = blob.getBinaryStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); is.close(); try { byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length()); textVal = Base64.getEncoder().encodeToString(buffer); } catch (SQLFeatureNotSupportedException exc) { textVal = Base64.getEncoder().encodeToString(baos.toByteArray()); } } } break; default: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DEFAULT_TYPE); textVal = rs.getString(j); isNull = textVal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } } } if (textVal != null) { text = doc.createTextNode(textVal); col.appendChild(text); } if (isKeyCol) { if (textVal != null) { if (colKey == null) { colKey = textVal; } else { colKey += "##" + textVal; } keyCols.put(String.valueOf(j), col); } } else { row.appendChild(col); } } if (noKey) { if (data == null) { data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS); parser.setAttribute(data, AbstractDBO.ID_NAME, id); } } else if ((colKey != null) && !colKey.equals(precKey)) { if (data != null) { docRoot.appendChild(data); } data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS); parser.setAttribute(data, AbstractDBO.ID_NAME, id); Element key = parser.createElementNS(doc, AbstractDBO.KEY_NAME, NS); data.appendChild(key); for (Entry<String, Element> keyColsEntry : keyCols.entrySet()) { key.appendChild(keyColsEntry.getValue()); } keyCols.clear(); precKey = colKey; } colKey = null; data.appendChild(row); rowCounter++; } if (data != null) { docRoot.appendChild(data); } return rowCounter; }
From source file:org.siphon.jssql.SqlExecutor.java
private ScriptObjectMirror rsToDataTable(ResultSet rs) throws SQLException, SqlExecutorException, ScriptException { ResultSetMetaData rsm = rs.getMetaData(); ScriptObjectMirror result = jsTypeUtil.newDataTable(); int c = 0;/*from w w w.jav a 2s . c o m*/ result.put("columns", columnListToNativeArray(rsm)); ScriptObjectMirror arr = jsTypeUtil.newArray(); NativeArray narr = arr.to(NativeArray.class); while (rs.next()) { ScriptObjectMirror item = jsTypeUtil.newObject(); for (int i = 1; i <= rsm.getColumnCount(); i++) { String cname = this.useColumnLabelAsName ? rsm.getColumnLabel(i) : rsm.getColumnName(i); String label = convertColumnName(cname); item.put(label, fieldValueToNativeObject(rsm.getColumnType(i), rs, cname)); } //NativeArray.pushObject(narr, item.to(ScriptObject.class)); arr.callMember("push", item); } result.put("rows", arr); return result; // JSON.stringify(result) }