List of usage examples for java.sql ResultSetMetaData getTableName
String getTableName(int column) throws SQLException;
From source file:SeeAccount.java
public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException { PrintWriter out = null;//from w w w. j a v a 2 s. co 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 testMediumUnsignedIntShouldBeInt() throws SQLException, IllegalArgumentException, IllegalAccessException { final ResultSetMetaData metadata = mock(ResultSetMetaData.class); when(metadata.getColumnCount()).thenReturn(1); when(metadata.getColumnType(1)).thenReturn(Types.INTEGER); when(metadata.getPrecision(1)).thenReturn(8); when(metadata.isSigned(1)).thenReturn(false); 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);/*ww w .j av a2 s.c o m*/ 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.apache.nifi.processors.standard.util.TestJdbcCommon.java
@Test public void testUnsignedIntShouldBeLong() throws SQLException, IllegalArgumentException, IllegalAccessException { final ResultSetMetaData metadata = mock(ResultSetMetaData.class); when(metadata.getColumnCount()).thenReturn(1); when(metadata.getColumnType(1)).thenReturn(Types.INTEGER); when(metadata.getPrecision(1)).thenReturn(10); when(metadata.isSigned(1)).thenReturn(false); 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 ww w. jav a 2s .c o m Schema.Field field = schema.getField("Col1"); Schema fieldSchema = field.schema(); Assert.assertEquals(2, fieldSchema.getTypes().size()); boolean foundLongSchema = false; boolean foundNullSchema = false; for (Schema type : fieldSchema.getTypes()) { if (type.getType().equals(Schema.Type.LONG)) { foundLongSchema = true; } else if (type.getType().equals(Schema.Type.NULL)) { foundNullSchema = true; } } assertTrue(foundLongSchema); assertTrue(foundNullSchema); }
From source file:org.jboss.dashboard.dataset.sql.SQLDataSet.java
public void load() throws Exception { DataSource targetDS = CoreServices.lookup().getDataSourceManager().getDataSource(dataSource); if (targetDS == null) return;/*from w ww. ja va2 s .c om*/ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; CodeBlockTrace trace = null; try { // Get the connection. conn = targetDS.getConnection(); // Execute the query. lastExecutedStmt = createSQLStatament(); trace = new SQLStatementTrace(lastExecutedStmt.getSQLSentence()).begin(); trace.addRuntimeConstraint(new DataSetLoadConstraints(this)); log.debug("Load data set from datasource=" + dataSource + " SQL=" + lastExecutedStmt.getSQLSentence()); stmt = lastExecutedStmt.getPreparedStatement(conn); rs = stmt.executeQuery(); // Get the properties definition. ResultSetMetaData meta = rs.getMetaData(); int propsSize = meta.getColumnCount(); SQLDataSet.this.setPropertySize(propsSize); for (int i = 0; i < propsSize; i++) { SQLDataProperty dp = createSQLProperty(); String propId = StringUtils.isNotBlank(meta.getColumnLabel(i + 1)) ? meta.getColumnLabel(i + 1) : meta.getColumnName(i + 1); dp.setPropertyId(propId.toLowerCase()); // dp.setPropertyId(meta.getColumnName(i + 1).toLowerCase()); dp.setType(meta.getColumnType(i + 1)); dp.setTableName(meta.getTableName(i + 1)); dp.setColumnName(meta.getColumnName(i + 1)); addProperty(dp, i); } // Get rows and populate the data set values. int index = 0; while (rs.next()) { Object[] row = new Object[propsSize]; for (int i = 0; i < propsSize; i++) row[i] = rs.getObject(i + 1); SQLDataSet.this.addRowValues(row); // Check load constraints (every 10,000 rows) if (++index == 10000) { trace.checkRuntimeConstraints(); index = 0; } } // Once we got the dataset initialized then calculate the domain for each property. for (int i = 0; i < properties.length; i++) { SQLDataProperty property = (SQLDataProperty) properties[i]; property.calculateDomain(); } } catch (Exception e) { if (lastExecutedStmt != null) { log.error("Error in load() SQLDataset. SQL = " + lastExecutedStmt.getSQLSentence(), e); } throw e; } finally { try { if (rs != null) rs.close(); } catch (Exception e) { log.warn("Error closing ResultSet: ", e); } try { if (stmt != null) stmt.close(); } catch (Exception e) { log.warn("Error closing PreparedStatement: ", e); } if (conn != null) { conn.close(); } if (trace != null) { trace.end(); } } }
From source file:com.cloudera.sqoop.manager.SqlManager.java
/** * Prints the contents of a ResultSet to the specified PrintWriter. * The ResultSet is closed at the end of this method. * @param results the ResultSet to print. * @param pw the location to print the data to. *//*from w w w .ja v a 2 s .c o m*/ protected void formatAndPrintResultSet(ResultSet results, PrintWriter pw) { try { try { int cols = results.getMetaData().getColumnCount(); pw.println("Got " + cols + " columns back"); if (cols > 0) { ResultSetMetaData rsmd = results.getMetaData(); String schema = rsmd.getSchemaName(1); String table = rsmd.getTableName(1); if (null != schema) { pw.println("Schema: " + schema); } if (null != table) { pw.println("Table: " + table); } } } catch (SQLException sqlE) { LOG.error("SQLException reading result metadata: " + sqlE.toString()); } try { new ResultSetPrinter().printResultSet(pw, results); } catch (IOException ioe) { LOG.error("IOException writing results: " + ioe.toString()); return; } } finally { try { results.close(); getConnection().commit(); } catch (SQLException sqlE) { LOG.warn("SQLException closing ResultSet: " + sqlE.toString()); } release(); } }
From source file:org.apache.kylin.query.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 a v a 2 s . 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++; } logger.info(sb.toString()); return count; }
From source file:com.streamsets.pipeline.stage.origin.jdbc.JdbcSource.java
private void validateResultSetMetadata(List<ConfigIssue> issues, Source.Context context, ResultSet rs) { Set<String> allTables = new HashSet<>(); try {//from ww w . j a v a2 s . c o m Set<String> columnLabels = new HashSet<>(); ResultSetMetaData metadata = rs.getMetaData(); int columnIdx = metadata.getColumnCount() + 1; while (--columnIdx > 0) { String columnLabel = metadata.getColumnLabel(columnIdx); if (columnLabels.contains(columnLabel)) { issues.add( context.createConfigIssue(Groups.JDBC.name(), QUERY, JdbcErrors.JDBC_31, columnLabel)); } else { columnLabels.add(columnLabel); } allTables.add(metadata.getTableName(columnIdx)); } if (!StringUtils.isEmpty(offsetColumn) && offsetColumn.contains(".")) { issues.add(context.createConfigIssue(Groups.JDBC.name(), OFFSET_COLUMN, JdbcErrors.JDBC_32, offsetColumn)); } else { rs.findColumn(offsetColumn); } } catch (SQLException e) { // Log a warning instead of an error because some implementations such as Oracle have implicit // "columns" such as ROWNUM that won't appear as part of the result set. LOG.warn(JdbcErrors.JDBC_33.getMessage(), offsetColumn, query); LOG.warn(jdbcUtil.formatSqlException(e)); } tableNames = StringUtils.join(allTables, ", "); }
From source file:at.ac.univie.isc.asio.engine.sql.WebRowSetWriter.java
private void columnDefinition(final int idx, final ResultSetMetaData context) throws XMLStreamException, SQLException { // @formatter:off xml.writeStartElement(WRS, "column-definition"); tag("column-index", idx); tag("auto-increment", context.isAutoIncrement(idx)); tag("case-sensitive", context.isCaseSensitive(idx)); tag("currency", context.isCurrency(idx)); tag("nullable", context.isNullable(idx)); tag("signed", context.isSigned(idx)); tag("searchable", context.isSearchable(idx)); tag("column-display-size", context.getColumnDisplaySize(idx)); tag("column-label", context.getColumnLabel(idx)); tag("column-name", context.getColumnName(idx)); tag("schema-name", context.getSchemaName(idx)); tag("column-precision", context.getPrecision(idx)); tag("column-scale", context.getScale(idx)); tag("table-name", context.getTableName(idx)); tag("catalog-name", context.getCatalogName(idx)); tag("column-type", context.getColumnType(idx)); tag("column-type-name", context.getColumnTypeName(idx)); xml.writeEndElement();//from w ww . ja va2s . c om // @formatter:on }
From source file:org.apache.hadoop.hive.jdbc.storagehandler.AtsdDBRecordReader.java
private ResultSet replaceDotsInColumnNames(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); if (columnCount > 0) { CachedRowSetImpl crs = new CachedRowSetImpl(); crs.populate(resultSet);/*from w w w. ja v a 2 s . c o m*/ RowSetMetaDataImpl rwsm = new RowSetMetaDataImpl(); rwsm.setColumnCount(columnCount); for (int i = 1; i <= columnCount; i++) { String columnName = metaData.getColumnName(i); if (columnName.contains(".")) { columnName = columnName.replaceAll("\\.", "\\$"); } rwsm.setColumnName(i, columnName); rwsm.setColumnLabel(i, metaData.getColumnLabel(i)); rwsm.setCatalogName(i, metaData.getCatalogName(i)); rwsm.setColumnType(i, metaData.getColumnType(i)); rwsm.setColumnTypeName(i, metaData.getColumnTypeName(i)); rwsm.setSchemaName(i, metaData.getSchemaName(i)); rwsm.setTableName(i, metaData.getTableName(i)); } crs.setMetaData(rwsm); return crs; } return resultSet; }
From source file:com.mmnaseri.dragonfly.fluent.impl.AbstractSelectQueryFinalizer.java
private <H> List<Map<Mapping, Object>> execute(SelectQueryExecution<E, H> selection) { final Connection connection = session.getConnection(); final PreparedStatement preparedStatement; try {// w w w.ja va 2 s .c o m final String sql = selection.getSql() + ";"; LogFactory.getLog(Statement.class).info("Preparing statement: " + sql); preparedStatement = connection.prepareStatement(sql); } catch (SQLException e) { throw new DatabaseNegotiationException("Failed to get a prepared statement from the database", e); } for (ParameterDescriptor descriptor : selection.getParameters()) { try { if (descriptor.getValue() == null) { preparedStatement.setNull(descriptor.getIndex(), descriptor.getSqlType()); } else { preparedStatement.setObject(descriptor.getIndex(), descriptor.getValue()); } } catch (SQLException e) { throw new StatementPreparationException( "Failed to prepare statement for parameter " + descriptor.getIndex(), e); } } final ResultSet resultSet; final ResultSetMetaData metaData; try { resultSet = preparedStatement.executeQuery(); } catch (SQLException e) { throw new DatabaseNegotiationException("Failed to retrieve the results from the data source", e); } try { metaData = resultSet.getMetaData(); } catch (SQLException e) { throw new DatabaseNegotiationException("Failed to get result set metadata for query", e); } final ArrayList<Map<Mapping, Object>> result = new ArrayList<Map<Mapping, Object>>(); while (true) { try { if (!resultSet.next()) { break; } final HashMap<Mapping, Object> map = new HashMap<Mapping, Object>(); for (int i = 1; i <= metaData.getColumnCount(); i++) { map.put(new ImmutableMapping(metaData.getTableName(i), metaData.getColumnName(i), metaData.getColumnLabel(i)), resultSet.getObject(i)); } result.add(map); } catch (SQLException e) { throw new DatabaseNegotiationException("Failed to get the next row", e); } } return result; }