List of usage examples for java.sql ResultSetMetaData getTableName
String getTableName(int column) throws SQLException;
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 w ww . j a v a 2 s. co m assertNotNull(schema.getField("ID")); assertNotNull(schema.getField("NOT_VCHARC")); // records name, should be result set first column table name assertEquals("TEST", schema.getName()); }
From source file:org.apache.calcite.avatica.jdbc.JdbcMeta.java
/** * Convert from JDBC metadata to Avatica columns. *///from w w w . java 2 s.c o m protected static List<ColumnMetaData> columns(ResultSetMetaData metaData) throws SQLException { if (metaData == null) { return Collections.emptyList(); } final List<ColumnMetaData> columns = new ArrayList<>(); for (int i = 1; i <= metaData.getColumnCount(); i++) { final SqlType sqlType = SqlType.valueOf(metaData.getColumnType(i)); final ColumnMetaData.Rep rep = ColumnMetaData.Rep.of(sqlType.internal); ColumnMetaData.AvaticaType t = ColumnMetaData.scalar(metaData.getColumnType(i), metaData.getColumnTypeName(i), rep); ColumnMetaData md = new ColumnMetaData(i - 1, 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.getPrecision(i), metaData.getScale(i), metaData.getTableName(i), metaData.getCatalogName(i), t, metaData.isReadOnly(i), metaData.isWritable(i), metaData.isDefinitelyWritable(i), metaData.getColumnClassName(i)); columns.add(md); } return columns; }
From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java
private List<LogMessageData> toLogMessageDataInternal(ResultSet rs, List<LogMessageData> logMessageData) { try {/*from w ww . j av a2 s .c om*/ // we will need the column names. java.sql.ResultSetMetaData rsmd = rs.getMetaData(); //loop through the ResultSet while (rs.next()) { //figure out how many columns there are int numColumns = rsmd.getColumnCount(); String tableName = rsmd.getTableName(1); LogMessageData obj = null; if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_01_NAME)) { obj = new LogMessageData_Partition_01(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_02_NAME)) { obj = new LogMessageData_Partition_02(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_03_NAME)) { obj = new LogMessageData_Partition_03(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_04_NAME)) { obj = new LogMessageData_Partition_04(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_05_NAME)) { obj = new LogMessageData_Partition_05(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_06_NAME)) { obj = new LogMessageData_Partition_06(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_07_NAME)) { obj = new LogMessageData_Partition_07(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_08_NAME)) { obj = new LogMessageData_Partition_08(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_09_NAME)) { obj = new LogMessageData_Partition_09(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_10_NAME)) { obj = new LogMessageData_Partition_10(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_11_NAME)) { obj = new LogMessageData_Partition_11(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_12_NAME)) { obj = new LogMessageData_Partition_12(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_13_NAME)) { obj = new LogMessageData_Partition_13(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_14_NAME)) { obj = new LogMessageData_Partition_14(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_15_NAME)) { obj = new LogMessageData_Partition_15(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_16_NAME)) { obj = new LogMessageData_Partition_16(); } else if (tableName.equals(DataBase.LOGMESSAGEDATA_PARTITION_17_NAME)) { obj = new LogMessageData_Partition_17(); } // loop through all the columns for (int i = 1; i < numColumns + 1; i++) { String column_name = rsmd.getColumnName(i); if (column_name.equals("ID")) { obj.setId(rs.getBigDecimal(column_name).longValueExact()); } if (column_name.equals("CONTENT")) { obj.setContent(rs.getNString(column_name)); } if (column_name.equals("LABEL")) { obj.setLabel(rs.getNString(column_name)); } if (column_name.equals("MIMETYPE")) { obj.setMimeType(rs.getNString(column_name)); } if (column_name.equals("MODIFIED")) { obj.setModified(rs.getBoolean(column_name)); } if (column_name.equals("CONTENTSIZE")) { obj.setContentSize(rs.getBigDecimal(column_name).longValueExact()); } if (column_name.equals("SEARCHABLE")) { obj.setSearchable(rs.getBoolean(column_name)); } if (column_name.equals("UTCLOCALTIMESTAMP")) { obj.setUtcLocalTimeStamp(rs.getTimestamp(column_name)); } if (column_name.equals("UTCSERVERTIMESTAMP")) { obj.setUtcServerTimeStamp(rs.getTimestamp(column_name)); } // if (column_name.equals("LOGMESSAGE_ID")) { // obj.setUtcServerTimeStamp(rs.getTimestamp(column_name)); // } } //end foreach logMessageData.add(obj); } //end while } catch (Exception e) { e.printStackTrace(); } return logMessageData; }
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 w w w. j a v a 2 s. c o 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); } } } } }
From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java
@Test public void testConvertToAvroStreamForShort() throws SQLException, IOException { final ResultSetMetaData metadata = mock(ResultSetMetaData.class); when(metadata.getColumnCount()).thenReturn(1); when(metadata.getColumnType(1)).thenReturn(Types.TINYINT); when(metadata.getColumnName(1)).thenReturn("t_int"); when(metadata.getTableName(1)).thenReturn("table"); final ResultSet rs = mock(ResultSet.class); when(rs.getMetaData()).thenReturn(metadata); final AtomicInteger counter = new AtomicInteger(1); Mockito.doAnswer(new Answer<Boolean>() { @Override/* w w w . j a v a2s .c o m*/ public Boolean answer(InvocationOnMock invocation) throws Throwable { return counter.getAndDecrement() > 0; } }).when(rs).next(); final short s = 25; when(rs.getObject(Mockito.anyInt())).thenReturn(s); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); JdbcCommon.convertToAvroStream(rs, baos, false); final byte[] serializedBytes = baos.toByteArray(); final InputStream instream = new ByteArrayInputStream(serializedBytes); final DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(); try (final DataFileStream<GenericRecord> dataFileReader = new DataFileStream<>(instream, datumReader)) { GenericRecord record = null; while (dataFileReader.hasNext()) { record = dataFileReader.next(record); assertEquals(Short.toString(s), record.get("t_int").toString()); } } }
From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java
@Test public void testCreateSchemaTypes() throws SQLException, IllegalArgumentException, IllegalAccessException { final Set<Integer> fieldsToIgnore = new HashSet<>(); fieldsToIgnore.add(Types.NULL); fieldsToIgnore.add(Types.OTHER); final Field[] fieldTypes = Types.class.getFields(); for (final Field field : fieldTypes) { final Object fieldObject = field.get(null); final int type = (int) fieldObject; if (fieldsToIgnore.contains(Types.NULL)) { continue; }// w w w . j ava2 s. c om final ResultSetMetaData metadata = mock(ResultSetMetaData.class); when(metadata.getColumnCount()).thenReturn(1); when(metadata.getColumnType(1)).thenReturn(type); when(metadata.getColumnName(1)).thenReturn(field.getName()); when(metadata.getTableName(1)).thenReturn("table"); final ResultSet rs = mock(ResultSet.class); when(rs.getMetaData()).thenReturn(metadata); try { JdbcCommon.createSchema(rs); } catch (final IllegalArgumentException | SQLException sqle) { sqle.printStackTrace(); Assert.fail("Failed when using type " + field.getName()); } } }
From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java
@Test public void testConvertToAvroStreamForBigDecimal() throws SQLException, IOException { final ResultSetMetaData metadata = mock(ResultSetMetaData.class); when(metadata.getColumnCount()).thenReturn(1); when(metadata.getColumnType(1)).thenReturn(Types.NUMERIC); when(metadata.getColumnName(1)).thenReturn("The.Chairman"); when(metadata.getTableName(1)).thenReturn("1the::table"); final ResultSet rs = mock(ResultSet.class); when(rs.getMetaData()).thenReturn(metadata); final AtomicInteger counter = new AtomicInteger(1); Mockito.doAnswer(new Answer<Boolean>() { @Override/*from w w w . j a v a2 s. com*/ public Boolean answer(InvocationOnMock invocation) throws Throwable { return counter.getAndDecrement() > 0; } }).when(rs).next(); final BigDecimal bigDecimal = new BigDecimal(38D); when(rs.getObject(Mockito.anyInt())).thenReturn(bigDecimal); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); JdbcCommon.convertToAvroStream(rs, baos, true); final byte[] serializedBytes = baos.toByteArray(); final InputStream instream = new ByteArrayInputStream(serializedBytes); final DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(); try (final DataFileStream<GenericRecord> dataFileReader = new DataFileStream<>(instream, datumReader)) { GenericRecord record = null; while (dataFileReader.hasNext()) { record = dataFileReader.next(record); assertEquals("_1the__table", record.getSchema().getName()); assertEquals(bigDecimal.toString(), record.get("The_Chairman").toString()); } } }
From source file:com.kylinolap.query.test.KylinTestBase.java
protected int output(ResultSet resultSet, boolean needDisplay) throws SQLException { int count = 0; ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); StringBuilder sb = new StringBuilder("\n"); if (needDisplay) { for (int i = 1; i <= columnCount; i++) { sb.append(metaData.getColumnName(i)); sb.append("-"); sb.append(metaData.getTableName(i)); sb.append("-"); sb.append(metaData.getColumnTypeName(i)); if (i < columnCount) { sb.append("\t"); } else { sb.append("\n"); }//from w w w. j av a2s . c om } } while (resultSet.next()) { if (needDisplay) { for (int i = 1; i <= columnCount; i++) { sb.append(resultSet.getString(i)); if (i < columnCount) { sb.append("\t"); } else { sb.append("\n"); } } } count++; } printInfo(sb.toString()); return count; }
From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java
@Test public void testSignedIntShouldBeInt() throws SQLException, IllegalArgumentException, IllegalAccessException { final ResultSetMetaData metadata = mock(ResultSetMetaData.class); when(metadata.getColumnCount()).thenReturn(1); when(metadata.getColumnType(1)).thenReturn(Types.INTEGER); when(metadata.isSigned(1)).thenReturn(true); when(metadata.getColumnName(1)).thenReturn("Col1"); when(metadata.getTableName(1)).thenReturn("Table1"); final ResultSet rs = mock(ResultSet.class); when(rs.getMetaData()).thenReturn(metadata); Schema schema = JdbcCommon.createSchema(rs); Assert.assertNotNull(schema);//from w w w .j av a2 s. c om Schema.Field field = schema.getField("Col1"); Schema fieldSchema = field.schema(); Assert.assertEquals(2, fieldSchema.getTypes().size()); boolean foundIntSchema = false; boolean foundNullSchema = false; for (Schema type : fieldSchema.getTypes()) { if (type.getType().equals(Schema.Type.INT)) { foundIntSchema = true; } else if (type.getType().equals(Schema.Type.NULL)) { foundNullSchema = true; } } assertTrue(foundIntSchema); assertTrue(foundNullSchema); }
From source file:org.jumpmind.metl.core.runtime.component.RdbmsReader.java
private ArrayList<String> getAttributeIds(String sql, ResultSetMetaData meta, Map<Integer, String> sqlEntityHints) throws SQLException { ArrayList<String> attributeIds = new ArrayList<String>(); boolean attributeFound = false; for (int i = 1; i <= meta.getColumnCount(); i++) { String columnName = meta.getColumnName(i); String tableName = meta.getTableName(i); if (sqlEntityHints.containsKey(i)) { String hint = sqlEntityHints.get(i); if (hint.indexOf(".") != -1) { tableName = hint.substring(0, hint.indexOf(".")); columnName = hint.substring(hint.indexOf(".") + 1); } else { tableName = hint;//from ww w . ja v a 2 s .c o m } } if (isBlank(tableName)) { /* * Some database driver do not support returning the table name * from the metadata. This code attempts to parse the entity * name from the sql */ tableName = getTableNameFromSql(sql); } if (matchOnColumnNameOnly) { attributeIds.addAll(getAttributeIds(columnName)); } else { if (StringUtils.isEmpty(tableName)) { throw new MisconfiguredException( "Table name could not be determined from metadata or hints. Please check column and hint. " + "(Note to SQL-Server users: metadata may not be returned unless you append 'FOR BROWSE' to the end of your query " + "or set 'useCursors=true' on the JDBC URL.)" + "Query column = " + i); } String attributeId = getAttributeId(tableName, columnName); if (attributeId != null) { attributeFound = true; } attributeIds.add(attributeId); } } if (!attributeFound) { throw new MisconfiguredException(String.format( "The SQL query results could not be mapped to an existing model entity. Please verify table columns " + "and hints match the configured output model, '%s'. SQL: '%s')", getOutputModel().getName(), sql)); } return attributeIds; }