List of usage examples for java.sql ResultSetMetaData getColumnType
int getColumnType(int column) throws SQLException;
From source file:org.apache.sqoop.connector.jdbc.oracle.util.OracleQueries.java
public static List<Column> getColDataTypes(Connection connection, OracleTable table, List<String> colNames) throws SQLException { List<Column> result = new ArrayList<Column>(); StringBuilder sb = new StringBuilder(); sb.append("SELECT "); for (int idx = 0; idx < colNames.size(); idx++) { if (idx > 0) { sb.append(","); }// w ww . j a v a 2s . co m sb.append(colNames.get(idx)); } sb.append(String.format(" FROM %s WHERE 0=1", table.toString())); String sql = sb.toString(); PreparedStatement statement = connection.prepareStatement(sql); try { ResultSetMetaData metadata = statement.getMetaData(); int numCols = metadata.getColumnCount(); for (int i = 1; i < numCols + 1; i++) { String colName = metadata.getColumnName(i); Column oracleColumn = OracleSqlTypesUtils.sqlTypeToSchemaType(metadata.getColumnType(i), colName, metadata.getPrecision(i), metadata.getScale(i)); result.add(oracleColumn); } } finally { statement.close(); } return result; }
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 .j av a 2 s.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.kylin.rest.util.HiveReroute.java
private void extractColumnMetadata(ResultSet resultSet, List<SelectedColumnMeta> columnMetas) throws SQLException { ResultSetMetaData metaData = null; int columnCount = 0; metaData = resultSet.getMetaData();//from w ww . j a v a 2s. c o 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:net.sf.jasperreports.engine.JRResultSetDataSource.java
/** * *///from w w w .ja va 2s . co m private Integer getColumnIndex(JRField field) throws JRException { String fieldName = field.getName(); Integer columnIndex = columnIndexMap.get(fieldName); if (columnIndex == null) { try { columnIndex = searchColumnByName(field); if (columnIndex == null) { columnIndex = searchColumnByLabel(field); } if (columnIndex == null) { columnIndex = searchColumnByIndex(field); } if (columnIndex == null) { columnIndex = searchColumnByName(fieldName); } if (columnIndex == null) { columnIndex = searchColumnByLabel(fieldName); } if (columnIndex == null && fieldName.startsWith(INDEXED_COLUMN_PREFIX)) { columnIndex = searchColumnByIndex(fieldName.substring(INDEXED_COLUMN_PREFIX_LENGTH)); } if (columnIndex == null) { throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_UNKNOWN_COLUMN_NAME, new Object[] { fieldName }); } } catch (SQLException e) { throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_METADATA_NOT_RETRIEVED, null, e); } if (log.isDebugEnabled()) { try { ResultSetMetaData metaData = resultSet.getMetaData(); log.debug("field " + fieldName + " has type " + metaData.getColumnType(columnIndex) + "/" + metaData.getColumnTypeName(columnIndex) + ", class " + metaData.getColumnClassName(columnIndex)); } catch (SQLException e) { log.debug("failed to read result set metadata", e); } } columnIndexMap.put(fieldName, columnIndex); } return columnIndex; }
From source file:org.springframework.jdbc.core.AbstractBeanPropertyRowMapper.java
protected Object doMapRow(ResultSet rs, int rowNumber) throws SQLException { if (getMappedClass() == null) throw new InvalidDataAccessApiUsageException("Target class was not specified - it is mandatory"); Object result;// ww w . j ava2 s .c o m try { result = this.defaultConstruct.newInstance((Object[]) null); } catch (IllegalAccessException e) { throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e); } catch (InvocationTargetException e) { throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e); } catch (InstantiationException e) { throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e); } ResultSetMetaData rsmd = rs.getMetaData(); int columns = rsmd.getColumnCount(); for (int i = 1; i <= columns; i++) { String column = JdbcUtils.lookupColumnName(rsmd, i).toLowerCase(); PersistentField fieldMeta = (PersistentField) this.mappedFields.get(column); if (fieldMeta != null) { BeanWrapper bw = new BeanWrapperImpl(mappedClass); bw.setWrappedInstance(result); fieldMeta.setSqlType(rsmd.getColumnType(i)); Object value = null; Class fieldType = fieldMeta.getJavaType(); if (fieldType.equals(String.class)) { value = rs.getString(column); } else if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) { value = new Byte(rs.getByte(column)); } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) { value = new Short(rs.getShort(column)); } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) { value = new Integer(rs.getInt(column)); } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) { value = new Long(rs.getLong(column)); } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) { value = new Float(rs.getFloat(column)); } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) { value = new Double(rs.getDouble(column)); } else if (fieldType.equals(BigDecimal.class)) { value = rs.getBigDecimal(column); } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) { value = (rs.getBoolean(column)) ? Boolean.TRUE : Boolean.FALSE; } else if (fieldType.equals(java.util.Date.class) || fieldType.equals(java.sql.Timestamp.class) || fieldType.equals(java.sql.Time.class) || fieldType.equals(Number.class)) { value = JdbcUtils.getResultSetValue(rs, rs.findColumn(column)); } if (value != null) { if (bw.isWritableProperty(fieldMeta.getFieldName())) { try { if (logger.isDebugEnabled() && rowNumber == 0) { logger.debug("Mapping column named \"" + column + "\"" + " containing values of SQL type " + fieldMeta.getSqlType() + " to property \"" + fieldMeta.getFieldName() + "\"" + " of type " + fieldMeta.getJavaType()); } bw.setPropertyValue(fieldMeta.getFieldName(), value); } catch (NotWritablePropertyException ex) { throw new DataRetrievalFailureException( "Unable to map column " + column + " to property " + fieldMeta.getFieldName(), ex); } } else { if (rowNumber == 0) { logger.warn("Unable to access the setter for " + fieldMeta.getFieldName() + ". Check that " + "set" + StringUtils.capitalize(fieldMeta.getFieldName()) + " is declared and has public access."); } } } } } return result; }
From source file:kr.co.bitnine.octopus.testutils.MemoryDatabaseTest.java
private void verifyTableEquals(JSONObject expectedTable, ResultSet actualRows) throws Exception { ResultSetMetaData actualRowsMetaData = actualRows.getMetaData(); JSONArray expectedSchema = (JSONArray) expectedTable.get("table-schema"); assertEquals(expectedSchema.size(), actualRowsMetaData.getColumnCount()); for (int i = 0; i < expectedSchema.size(); i++) assertEquals(expectedSchema.get(i), actualRowsMetaData.getColumnName(i + 1)); for (Object rowObj : (JSONArray) expectedTable.get("table-rows")) { JSONArray row = (JSONArray) rowObj; actualRows.next();// w ww.ja v a 2s. c om for (int i = 0; i < row.size(); i++) { Object expected = row.get(i); Object actual; int sqlType = actualRowsMetaData.getColumnType(i + 1); switch (sqlType) { case Types.INTEGER: if (expected instanceof Boolean) expected = (long) ((Boolean) expected ? 1 : 0); actual = actualRows.getLong(i + 1); break; case Types.NULL: case Types.FLOAT: case Types.VARCHAR: actual = actualRows.getObject(i + 1); break; default: throw new RuntimeException("java.sql.Types " + sqlType + " is not supported"); } assertEquals(expected, actual); } } assertFalse(actualRows.next()); }
From source file:org.apache.kylin.rest.adhoc.AdHocRunnerJdbcImpl.java
@Override public void executeQuery(String query, List<List<String>> results, List<SelectedColumnMeta> columnMetas) throws Exception { Statement statement = null;/* www . ja v a2 s .c om*/ Connection connection = this.getConnection(); ResultSet resultSet = null; try { statement = connection.createStatement(); resultSet = statement.executeQuery(query); extractResults(resultSet, results); } catch (SQLException sqlException) { throw sqlException; } //extract column metadata ResultSetMetaData metaData = null; int columnCount = 0; try { metaData = resultSet.getMetaData(); 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)); } } catch (SQLException sqlException) { throw sqlException; } closeConnection(connection); }
From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java
@Test public void testCreateSchemaNoTableName() throws ClassNotFoundException, SQLException { final ResultSet resultSet = mock(ResultSet.class); final ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSetMetaData.getTableName(1)).thenReturn(""); when(resultSetMetaData.getColumnType(1)).thenReturn(Types.INTEGER); when(resultSetMetaData.getColumnName(1)).thenReturn("ID"); final Schema schema = JdbcCommon.createSchema(resultSet); assertNotNull(schema);//w ww .j ava 2s . co m // records name, should be result set first column table name assertEquals("NiFi_ExecuteSQL_Record", schema.getName()); }
From source file:SeeAccount.java
public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException { PrintWriter out = null;/*from w w w. j ava 2s.c o m*/ Connection connection = null; Statement statement = null; ResultSet rs; try { outResponse.setContentType("text/html"); out = outResponse.getWriter(); Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB"); connection = ds.getConnection(); statement = connection.createStatement(); rs = statement.executeQuery("SELECT * FROM acc_acc"); ResultSetMetaData md = rs.getMetaData(); out.println("<HTML><HEAD><TITLE> Thumbnail Identification Record</TITLE></HEAD>"); out.println("<BODY>"); out.println("Account Information:<BR>"); out.println("<table>"); out.println("<tr><td>"); for (int i = 1; i <= md.getColumnCount(); i++) { out.println("Column #" + i + "<BR>"); out.println("getColumnName : " + md.getColumnName(i) + "<BR>"); out.println("getColumnClassName : " + md.getColumnClassName(i) + "<BR>"); out.println("getColumnDisplaySize : " + md.getColumnDisplaySize(i) + "<BR>"); out.println("getColumnType : " + md.getColumnType(i) + "<BR>"); out.println("getTableName : " + md.getTableName(i) + "<BR>"); out.println("<HR>"); } out.println("</BODY></HTML>"); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java
@Test public void testCreateSchemaOnlyColumnLabel() throws ClassNotFoundException, SQLException { final ResultSet resultSet = mock(ResultSet.class); final ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSetMetaData.getColumnCount()).thenReturn(2); when(resultSetMetaData.getTableName(1)).thenReturn("TEST"); when(resultSetMetaData.getColumnType(1)).thenReturn(Types.INTEGER); when(resultSetMetaData.getColumnName(1)).thenReturn(""); when(resultSetMetaData.getColumnLabel(1)).thenReturn("ID"); when(resultSetMetaData.getColumnType(2)).thenReturn(Types.VARCHAR); when(resultSetMetaData.getColumnName(2)).thenReturn("VCHARC"); when(resultSetMetaData.getColumnLabel(2)).thenReturn("NOT_VCHARC"); final Schema schema = JdbcCommon.createSchema(resultSet); assertNotNull(schema);//from ww w. ja v a 2s .com assertNotNull(schema.getField("ID")); assertNotNull(schema.getField("NOT_VCHARC")); // records name, should be result set first column table name assertEquals("TEST", schema.getName()); }