List of usage examples for java.sql ResultSetMetaData getColumnTypeName
String getColumnTypeName(int column) throws SQLException;
From source file:com.gzj.tulip.jade.rowmapper.MapEntryColumnRowMapper.java
public Object mapRow(ResultSet rs, int rowNum) throws SQLException { // ?/* w w w. ja v a2 s . c om*/ if (rowNum == 0) { ResultSetMetaData rsmd = rs.getMetaData(); int nrOfColumns = rsmd.getColumnCount(); if (nrOfColumns != 2) { throw new IncorrectResultSetColumnCountException(2, nrOfColumns); } if (StringUtils.isNotEmpty(keyColumn)) { keyColumnIndex = rs.findColumn(keyColumn); if (keyColumnIndex == 1) { valueColumnIndex = 2; } else if (keyColumnIndex == 2) { valueColumnIndex = 1; } else { throw new IllegalArgumentException( String.format("wrong key name %s for method: %s ", keyColumn, modifier.getMethod())); } keyColumn = null; } if (logger.isDebugEnabled()) { logger.debug(String.format("keyIndex=%s; valueIndex=%s; for method: %s ", keyColumnIndex, valueColumnIndex, modifier.getMethod())); } } // JDBC ResultSet ? Key Object key = JdbcUtils.getResultSetValue(rs, keyColumnIndex, keyType); if (key != null && !keyType.isInstance(key)) { ResultSetMetaData rsmd = rs.getMetaData(); throw new TypeMismatchDataAccessException( // NL "Type mismatch affecting row number " + rowNum + " and column type '" + rsmd.getColumnTypeName(keyColumnIndex) + "' expected type is '" + keyType + "'"); } // JDBC ResultSet ? Value Object value = JdbcUtils.getResultSetValue(rs, valueColumnIndex, valueType); if (value != null && !valueType.isInstance(value)) { ResultSetMetaData rsmd = rs.getMetaData(); throw new TypeMismatchDataAccessException( // NL "Type mismatch affecting row number " + rowNum + " and column type '" + rsmd.getColumnTypeName(valueColumnIndex) + "' expected type is '" + valueType + "'"); } // key?null?? return new MapEntryImpl<Object, Object>(key, value); }
From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java
public List<ColumnVO> getColumnsMetaDataExceptGeom(String sql, String geometryName) throws Exception { Exception error = null;/*from w w w. ja va 2 s.co m*/ List<ColumnVO> tableColumns = new LinkedList<ColumnVO>(); Connection connection = null; PreparedStatement preparedStmnt = null; try { DataSource dataSource = poolDataSources.get(schemaId); connection = dataSource.getConnection(); connection.setAutoCommit(false); preparedStmnt = connection.prepareStatement(sql); ResultSet rs = preparedStmnt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); String geometryFieldName = geometryName; if (StringUtils.isEmpty(geometryFieldName)) { geometryFieldName = "the_geom"; } for (int i = 1; i <= rsmd.getColumnCount(); i++) { String columnName = rsmd.getColumnName(i); if (!columnName.equals(geometryFieldName)) { String columnType = rsmd.getColumnTypeName(i); int columnSqlType = rsmd.getColumnType(i); int columnLength = rsmd.getColumnDisplaySize(i); int columnPrecision = rsmd.getPrecision(i); ColumnVO column = new ColumnVO(); column.setNameOnTable(columnName); column.setType(columnType); column.setSqlType(columnSqlType); column.setLength(columnLength); column.setPrecision(columnPrecision); column.setInTable(true); tableColumns.add(column); } } } catch (SQLException e) { error = e; } finally { if (preparedStmnt != null) { try { preparedStmnt.close(); } catch (SQLException se2) { log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage())); } } if (connection != null) { try { if (error != null) { connection.rollback(); } } catch (SQLException se) { log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage())); } try { connection.close(); } catch (SQLException se) { log.warn("Se produjo un error al intentar cerrar la conexin: " .concat(se.getLocalizedMessage())); } } } if (error != null) { throw error; } return tableColumns; }
From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java
public void testResultSetMetaData() throws SQLException { Statement stmt = con.createStatement(); ResultSet res = stmt.executeQuery("select c1, c2, c3, c4, c5 as a, c6, c7, c8, c9, c10, c11, c12, " + "c1*2, sentences(null, null, null) as b, c17, c18, c20 from " + dataTypeTableName + " limit 1"); ResultSetMetaData meta = res.getMetaData(); ResultSet colRS = con.getMetaData().getColumns(null, null, dataTypeTableName.toLowerCase(), null); assertEquals(17, meta.getColumnCount()); assertTrue(colRS.next());// ww w . ja va2 s. c o m assertEquals("c1", meta.getColumnName(1)); assertEquals(Types.INTEGER, meta.getColumnType(1)); assertEquals("int", meta.getColumnTypeName(1)); assertEquals(11, meta.getColumnDisplaySize(1)); assertEquals(10, meta.getPrecision(1)); assertEquals(0, meta.getScale(1)); assertEquals("c1", colRS.getString("COLUMN_NAME")); assertEquals(Types.INTEGER, colRS.getInt("DATA_TYPE")); assertEquals("int", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(1), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(1), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c2", meta.getColumnName(2)); assertEquals("boolean", meta.getColumnTypeName(2)); assertEquals(Types.BOOLEAN, meta.getColumnType(2)); assertEquals(1, meta.getColumnDisplaySize(2)); assertEquals(1, meta.getPrecision(2)); assertEquals(0, meta.getScale(2)); assertEquals("c2", colRS.getString("COLUMN_NAME")); assertEquals(Types.BOOLEAN, colRS.getInt("DATA_TYPE")); assertEquals("boolean", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(2), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(2), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c3", meta.getColumnName(3)); assertEquals(Types.DOUBLE, meta.getColumnType(3)); assertEquals("double", meta.getColumnTypeName(3)); assertEquals(25, meta.getColumnDisplaySize(3)); assertEquals(15, meta.getPrecision(3)); assertEquals(15, meta.getScale(3)); assertEquals("c3", colRS.getString("COLUMN_NAME")); assertEquals(Types.DOUBLE, colRS.getInt("DATA_TYPE")); assertEquals("double", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(3), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(3), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c4", meta.getColumnName(4)); assertEquals(Types.VARCHAR, meta.getColumnType(4)); assertEquals("string", meta.getColumnTypeName(4)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(4)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(4)); assertEquals(0, meta.getScale(4)); assertEquals("c4", colRS.getString("COLUMN_NAME")); assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE")); assertEquals("string", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(4), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(4), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("a", meta.getColumnName(5)); assertEquals(Types.VARCHAR, meta.getColumnType(5)); assertEquals("string", meta.getColumnTypeName(5)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(5)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(5)); assertEquals(0, meta.getScale(5)); assertEquals("c5", colRS.getString("COLUMN_NAME")); assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE")); assertEquals("array<int>", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(5), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(5), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c6", meta.getColumnName(6)); assertEquals(Types.VARCHAR, meta.getColumnType(6)); assertEquals("string", meta.getColumnTypeName(6)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(6)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(6)); assertEquals(0, meta.getScale(6)); assertEquals("c6", colRS.getString("COLUMN_NAME")); assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE")); assertEquals("map<int,string>", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(6), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(6), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c7", meta.getColumnName(7)); assertEquals(Types.VARCHAR, meta.getColumnType(7)); assertEquals("string", meta.getColumnTypeName(7)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(7)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(7)); assertEquals(0, meta.getScale(7)); assertEquals("c7", colRS.getString("COLUMN_NAME")); assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE")); assertEquals("map<string,string>", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(7), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(7), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c8", meta.getColumnName(8)); assertEquals(Types.VARCHAR, meta.getColumnType(8)); assertEquals("string", meta.getColumnTypeName(8)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(8)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(8)); assertEquals(0, meta.getScale(8)); assertEquals("c8", colRS.getString("COLUMN_NAME")); assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE")); assertEquals("struct<r:string,s:int,t:double>", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(8), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(8), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c9", meta.getColumnName(9)); assertEquals(Types.TINYINT, meta.getColumnType(9)); assertEquals("tinyint", meta.getColumnTypeName(9)); assertEquals(4, meta.getColumnDisplaySize(9)); assertEquals(3, meta.getPrecision(9)); assertEquals(0, meta.getScale(9)); assertEquals("c9", colRS.getString("COLUMN_NAME")); assertEquals(Types.TINYINT, colRS.getInt("DATA_TYPE")); assertEquals("tinyint", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(9), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(9), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c10", meta.getColumnName(10)); assertEquals(Types.SMALLINT, meta.getColumnType(10)); assertEquals("smallint", meta.getColumnTypeName(10)); assertEquals(6, meta.getColumnDisplaySize(10)); assertEquals(5, meta.getPrecision(10)); assertEquals(0, meta.getScale(10)); assertEquals("c10", colRS.getString("COLUMN_NAME")); assertEquals(Types.SMALLINT, colRS.getInt("DATA_TYPE")); assertEquals("smallint", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(10), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(10), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c11", meta.getColumnName(11)); assertEquals(Types.FLOAT, meta.getColumnType(11)); assertEquals("float", meta.getColumnTypeName(11)); assertEquals(24, meta.getColumnDisplaySize(11)); assertEquals(7, meta.getPrecision(11)); assertEquals(7, meta.getScale(11)); assertEquals("c11", colRS.getString("COLUMN_NAME")); assertEquals(Types.FLOAT, colRS.getInt("DATA_TYPE")); assertEquals("float", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(11), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(11), colRS.getInt("DECIMAL_DIGITS")); assertTrue(colRS.next()); assertEquals("c12", meta.getColumnName(12)); assertEquals(Types.BIGINT, meta.getColumnType(12)); assertEquals("bigint", meta.getColumnTypeName(12)); assertEquals(20, meta.getColumnDisplaySize(12)); assertEquals(19, meta.getPrecision(12)); assertEquals(0, meta.getScale(12)); assertEquals("c12", colRS.getString("COLUMN_NAME")); assertEquals(Types.BIGINT, colRS.getInt("DATA_TYPE")); assertEquals("bigint", colRS.getString("TYPE_NAME").toLowerCase()); assertEquals(meta.getPrecision(12), colRS.getInt("COLUMN_SIZE")); assertEquals(meta.getScale(12), colRS.getInt("DECIMAL_DIGITS")); assertEquals("_c12", meta.getColumnName(13)); assertEquals(Types.INTEGER, meta.getColumnType(13)); assertEquals("int", meta.getColumnTypeName(13)); assertEquals(11, meta.getColumnDisplaySize(13)); assertEquals(10, meta.getPrecision(13)); assertEquals(0, meta.getScale(13)); assertEquals("b", meta.getColumnName(14)); assertEquals(Types.VARCHAR, meta.getColumnType(14)); assertEquals("string", meta.getColumnTypeName(14)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(14)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(14)); assertEquals(0, meta.getScale(14)); assertEquals("c17", meta.getColumnName(15)); assertEquals(Types.TIMESTAMP, meta.getColumnType(15)); assertEquals("timestamp", meta.getColumnTypeName(15)); assertEquals(29, meta.getColumnDisplaySize(15)); assertEquals(29, meta.getPrecision(15)); assertEquals(9, meta.getScale(15)); assertEquals("c18", meta.getColumnName(16)); assertEquals(Types.DECIMAL, meta.getColumnType(16)); assertEquals("decimal", meta.getColumnTypeName(16)); assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(16)); assertEquals(Integer.MAX_VALUE, meta.getPrecision(16)); assertEquals(Integer.MAX_VALUE, meta.getScale(16)); assertEquals("c20", meta.getColumnName(17)); assertEquals(Types.DATE, meta.getColumnType(17)); assertEquals("date", meta.getColumnTypeName(17)); assertEquals(10, meta.getColumnDisplaySize(17)); assertEquals(10, meta.getPrecision(17)); assertEquals(0, meta.getScale(17)); for (int i = 1; i <= meta.getColumnCount(); i++) { assertFalse(meta.isAutoIncrement(i)); assertFalse(meta.isCurrency(i)); assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(i)); } }
From source file:org.seasar.dbflute.logic.sql2entity.cmentity.DfCustomizeEntityMetaExtractor.java
public Map<String, DfColumnMeta> extractColumnMetaInfoMap(ResultSet rs, String sql, DfForcedJavaNativeProvider forcedJavaNativeProvider) throws SQLException { final Map<String, DfColumnMeta> columnMetaInfoMap = StringKeyMap.createAsFlexibleOrdered(); final ResultSetMetaData md = rs.getMetaData(); for (int i = 1; i <= md.getColumnCount(); i++) { final DfColumnMeta metaInfo = new DfColumnMeta(); String sql2EntityRelatedTableName = null; try {// w w w . ja va2s . c om sql2EntityRelatedTableName = md.getTableName(i); } catch (SQLException ignored) { // Because this table name is not required. This is for classification. String msg = "ResultSetMetaData.getTableName(" + i + ") threw the exception:"; msg = msg + " " + ignored.getMessage(); _log.info(msg); } metaInfo.setSql2EntityRelatedTableName(sql2EntityRelatedTableName); String columnName = md.getColumnLabel(i); final String relatedColumnName = md.getColumnName(i); metaInfo.setSql2EntityRelatedColumnName(relatedColumnName); if (columnName == null || columnName.trim().length() == 0) { columnName = relatedColumnName; } if (columnName == null || columnName.trim().length() == 0) { final String ln = ln(); String msg = "The columnName is invalid: columnName=" + columnName + ln; msg = msg + "ResultSetMetaData returned invalid value." + ln; msg = msg + "sql=" + sql; throw new IllegalStateException(msg); } metaInfo.setColumnName(columnName); final int columnType = md.getColumnType(i); metaInfo.setJdbcDefValue(columnType); final String columnTypeName = md.getColumnTypeName(i); metaInfo.setDbTypeName(columnTypeName); int columnSize = md.getPrecision(i); if (!DfColumnExtractor.isColumnSizeValid(columnSize)) { // ex) sum(COLUMN) columnSize = md.getColumnDisplaySize(i); } metaInfo.setColumnSize(columnSize); final int scale = md.getScale(i); metaInfo.setDecimalDigits(scale); if (forcedJavaNativeProvider != null) { final String sql2entityForcedJavaNative = forcedJavaNativeProvider.provide(columnName); metaInfo.setSql2EntityForcedJavaNative(sql2entityForcedJavaNative); } // column comment is not set here (no comment on meta data) // if select column comment is specified, comment will be set later columnMetaInfoMap.put(columnName, metaInfo); } return columnMetaInfoMap; }
From source file:org.apache.kylin.rest.service.QueryService.java
/** * @param correctedSql/*w w w . ja v a 2 s .c o m*/ * @param sqlRequest * @return * @throws Exception */ private SQLResponse execute(String correctedSql, SQLRequest sqlRequest) throws Exception { Connection conn = null; Statement stat = null; ResultSet resultSet = null; Boolean isPushDown = false; List<List<String>> results = Lists.newArrayList(); List<SelectedColumnMeta> columnMetas = Lists.newArrayList(); try { conn = cacheService.getOLAPDataSource(sqlRequest.getProject()).getConnection(); // special case for prepare query. if (BackdoorToggles.getPrepareOnly()) { return getPrepareOnlySqlResponse(correctedSql, conn, isPushDown, results, columnMetas); } stat = conn.createStatement(); processStatementAttr(stat, sqlRequest); resultSet = stat.executeQuery(correctedSql); ResultSetMetaData metaData = resultSet.getMetaData(); int 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), metaData.isSearchable(i), metaData.isCurrency(i), metaData.isNullable(i), metaData.isSigned(i), metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i), metaData.getSchemaName(i), metaData.getCatalogName(i), metaData.getTableName(i), metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i), metaData.isWritable(i), metaData.isDefinitelyWritable(i))); } // fill in results while (resultSet.next()) { List<String> oneRow = Lists.newArrayListWithCapacity(columnCount); for (int i = 0; i < columnCount; i++) { oneRow.add((resultSet.getString(i + 1))); } results.add(oneRow); } } catch (SQLException sqlException) { isPushDown = PushDownUtil.doPushDownQuery(sqlRequest.getProject(), correctedSql, results, columnMetas, sqlException); } finally { close(resultSet, stat, conn); } return getSqlResponse(isPushDown, results, columnMetas); }
From source file:com.hangum.tadpole.engine.sql.util.resultset.ResultSetUtils.java
/** * column of type//from w w w.j a v a 2 s . com * * @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:org.nuclos.server.dblayer.impl.standard.StandardSqlDBAccess.java
@Override public ResultVO executePlainQueryAsResultVO(String sql, int maxRows) throws DbException { return executePlainQuery(sql, maxRows, new ResultSetRunner<ResultVO>() { @Override// ww w . j a v a 2s . c o m public ResultVO perform(ResultSet rs) throws SQLException { ResultVO result = new ResultVO(); ResultSetMetaData metadata = rs.getMetaData(); Class<?>[] javaTypes = new Class<?>[metadata.getColumnCount()]; for (int i = 0; i < metadata.getColumnCount(); i++) { ResultColumnVO column = new ResultColumnVO(); column.setColumnLabel(metadata.getColumnLabel(i + 1)); DbGenericType type = getDbGenericType(metadata.getColumnType(i + 1), metadata.getColumnTypeName(i + 1)); if (type != null) { Class<?> javaType = type.getPreferredJavaType(); // override java type here @todo this is not the right place. if (type == DbGenericType.NUMERIC) { if (metadata.getScale(i + 1) == 0) javaType = Integer.class; else javaType = Double.class; } column.setColumnClassName(javaType.getName()); javaTypes[i] = javaType; } else { column.setColumnClassName(metadata.getColumnClassName(i + 1)); javaTypes[i] = Object.class; } result.addColumn(column); } while (rs.next()) { final Object[] values = new Object[javaTypes.length]; for (int i = 0; i < values.length; i++) { values[i] = getResultSetValue(rs, i + 1, javaTypes[i]); } result.addRow(values); } return result; } }); }
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 w ww . j ava 2s .co m*/ return arr; }
From source file:ro.nextreports.designer.dbviewer.DefaultDBViewer.java
public List<DBColumn> getColumns(String schema, String table) throws NextSqlException, MalformedTableNameException { Connection con;// w w w. jav a 2s . c o m List<DBColumn> columns = new ArrayList<DBColumn>(); String schemaName; String escapedTableName; try { con = Globals.getConnection(); if (schema == null) { schemaName = Globals.getConnection().getMetaData().getUserName(); } else { schemaName = schema; } Dialect dialect = Globals.getDialect(); if (dialect.isKeyWord(table)) { escapedTableName = dialect.getEscapedKeyWord(table); } else { escapedTableName = table; } } catch (Exception e) { throw new NextSqlException("Could not retrieve connection.", e); } ResultSet rs = null; Statement stmt = null; List<String> keyColumns = new ArrayList<String>(); try { // primary keys DatabaseMetaData dbmd = con.getMetaData(); rs = dbmd.getPrimaryKeys(null, schemaName, table); while (rs.next()) { keyColumns.add(rs.getString("COLUMN_NAME")); } closeResultSet(rs); // foreign keys rs = dbmd.getImportedKeys(null, schemaName, table); List<String> foreignColumns = new ArrayList<String>(); HashMap<String, DBForeignColumnInfo> fkMap = new HashMap<String, DBForeignColumnInfo>(); while (rs.next()) { String fkSchema = rs.getString("FKTABLE_SCHEM"); String fkTable = rs.getString("FKTABLE_NAME"); String fkColumn = rs.getString("FKCOLUMN_NAME"); String pkSchema = rs.getString("PKTABLE_SCHEM"); String pkTable = rs.getString("PKTABLE_NAME"); String pkColumn = rs.getString("PKCOLUMN_NAME"); DBForeignColumnInfo fkInfo = new DBForeignColumnInfo(fkSchema, fkTable, fkColumn, pkSchema, pkTable, pkColumn); //System.out.println("fkInfo : " + fkInfo); foreignColumns.add(fkColumn); fkMap.put(fkColumn, fkInfo); } closeResultSet(rs); // column names with index rs = dbmd.getIndexInfo(null, schemaName, table, false, true); List<String> indexes = new ArrayList<String>(); while (rs.next()) { String indexName = rs.getString(9); if (indexName != null) { indexes.add(indexName); } } closeResultSet(rs); DataSource ds = DefaultDataSourceManager.getInstance().getConnectedDataSource(); String header = ""; stmt = con.createStatement(); try { // workaround if a table name contains spaces if (escapedTableName.indexOf(" ") != -1) { escapedTableName = "\"" + escapedTableName + "\""; } String prefix = ""; if (!NO_SCHEMA_NAME.equals(schemaName)) { prefix = schemaName; } if (prefix.indexOf(" ") != -1) { prefix = "\"" + prefix + "\""; } if (!"".equals(prefix)) { prefix = prefix + "."; } if (ds.getDriver().equals(CSVDialect.DRIVER_CLASS)) { header = (String) ds.getProperties().get("headerline"); if (header == null) { header = ""; } } if (header.isEmpty()) { String s = "SELECT * FROM " + prefix + escapedTableName + " WHERE 1 = 0"; LOG.info("getColumns[ " + s + "]"); rs = stmt.executeQuery(s); } } catch (SQLException e) { e.printStackTrace(); throw new MalformedTableNameException(e); } if (header.isEmpty()) { ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int col = 1; col <= columnCount; col++) { String name = rsmd.getColumnLabel(col); int length = rsmd.getColumnDisplaySize(col); int precision = rsmd.getPrecision(col); int scale = rsmd.getScale(col); boolean isPrimaryKey = false; boolean isForeignKey = false; boolean isIndex = false; if (keyColumns.contains(name)) { isPrimaryKey = true; } DBForeignColumnInfo fkInfo = null; if (foreignColumns.contains(name)) { isForeignKey = true; fkInfo = fkMap.get(name); } if (indexes.contains(name)) { isIndex = true; } DBColumn column = new DBColumn(schemaName, table, name, rsmd.getColumnTypeName(col), isPrimaryKey, isForeignKey, isIndex, fkInfo, length, precision, scale); columns.add(column); } } else { String columnTypes = (String) ds.getProperties().get("columnTypes"); String[] names = header.split(","); String[] types = new String[names.length]; for (int i = 0; i < types.length; i++) { types[i] = "String"; } if ((columnTypes != null) && !columnTypes.isEmpty()) { types = columnTypes.split(","); } for (int i = 0; i < names.length; i++) { DBColumn column = new DBColumn(schemaName, table, names[i], types[i], false, false, false, null, 20, 0, 0); columns.add(column); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); e.printStackTrace(); throw new NextSqlException("SQL Exception: " + e.getMessage(), e); } finally { closeResultSet(rs); closeStatement(stmt); } return columns; }
From source file:org.openecomp.sdnc.sli.resource.sql.SqlResource.java
public void saveCachedRowSetToCtx(CachedRowSet results, SvcLogicContext ctx, String prefix, DbLibService dblibSvc) throws SQLException { if (ctx != null) { if ((prefix != null) && prefix.endsWith("[]")) { // Return an array. String pfx = prefix.substring(0, prefix.length() - 2); int idx = 0; do {//from ww w .j a v a 2 s. co m ResultSetMetaData rsMeta = results.getMetaData(); int numCols = rsMeta.getColumnCount(); for (int i = 0; i < numCols; i++) { String colValue = null; String tableName = rsMeta.getTableName(i + 1); if (rsMeta.getColumnType(i + 1) == java.sql.Types.VARBINARY) { colValue = decryptColumn(tableName, rsMeta.getColumnName(i + 1), results.getBytes(i + 1), dblibSvc); } else { colValue = results.getString(i + 1); } LOG.debug("Setting " + pfx + "[" + idx + "]." + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-") + " = " + colValue); ctx.setAttribute(pfx + "[" + idx + "]." + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-"), colValue); } idx++; } while (results.next()); LOG.debug("Setting " + pfx + "_length = " + idx); ctx.setAttribute(pfx + "_length", "" + idx); } else { ResultSetMetaData rsMeta = results.getMetaData(); int numCols = rsMeta.getColumnCount(); for (int i = 0; i < numCols; i++) { String colValue = null; String tableName = rsMeta.getTableName(i + 1); if ("VARBINARY".equalsIgnoreCase(rsMeta.getColumnTypeName(i + 1))) { colValue = decryptColumn(tableName, rsMeta.getColumnName(i + 1), results.getBytes(i + 1), dblibSvc); } else { colValue = results.getString(i + 1); } if (prefix != null) { LOG.debug("Setting " + prefix + "." + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-") + " = " + colValue); ctx.setAttribute(prefix + "." + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-"), colValue); } else { LOG.debug( "Setting " + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-") + " = " + colValue); ctx.setAttribute(rsMeta.getColumnLabel(i + 1).replaceAll("_", "-"), colValue); } } } } }