List of usage examples for java.sql ResultSetMetaData getColumnName
String getColumnName(int column) throws SQLException;
From source file:org.apache.sqoop.connector.jdbc.GenericJdbcToInitializer.java
@Override public Schema getSchema(InitializerContext context, LinkConfiguration linkConfig, ToJobConfiguration toJobConfig) { configureJdbcProperties(context.getContext(), linkConfig, toJobConfig); String schemaName = toJobConfig.toJobConfig.tableName; if (schemaName == null) { throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0019, "Table name extraction not supported yet."); }//from w w w. j a v a2 s. com if (toJobConfig.toJobConfig.schemaName != null) { schemaName = toJobConfig.toJobConfig.schemaName + "." + schemaName; } Schema schema = new Schema(schemaName); ResultSet rs = null; ResultSetMetaData rsmt = null; try { rs = executor.executeQuery("SELECT * FROM " + schemaName + " WHERE 1 = 0"); rsmt = rs.getMetaData(); for (int i = 1; i <= rsmt.getColumnCount(); i++) { Column column = SqlTypesUtils.sqlTypeToAbstractType(rsmt.getColumnType(i)); String columnName = rsmt.getColumnName(i); if (columnName == null || columnName.equals("")) { columnName = rsmt.getColumnLabel(i); if (null == columnName) { columnName = "Column " + i; } } column.setName(columnName); schema.addColumn(column); } return schema; } catch (SQLException e) { throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0016, e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.info("Ignoring exception while closing ResultSet", e); } } } }
From source file:org.apache.syncope.core.util.ContentExporter.java
private void doExportTable(final TransformerHandler handler, final Connection conn, final String tableName, final String whereClause) throws SQLException, SAXException { LOG.debug("Export table {}", tableName); AttributesImpl attrs = new AttributesImpl(); PreparedStatement stmt = null; ResultSet rs = null;// w w w .j av a 2s . co m ResultSet pkeyRS = null; try { // ------------------------------------ // retrieve primary keys to perform an ordered select final DatabaseMetaData meta = conn.getMetaData(); pkeyRS = meta.getPrimaryKeys(null, null, tableName); final StringBuilder orderBy = new StringBuilder(); while (pkeyRS.next()) { final String columnName = pkeyRS.getString("COLUMN_NAME"); if (columnName != null) { if (orderBy.length() > 0) { orderBy.append(","); } orderBy.append(columnName); } } // ------------------------------------ StringBuilder query = new StringBuilder(); query.append("SELECT * FROM ").append(tableName).append(" a"); if (StringUtils.isNotBlank(whereClause)) { query.append(" WHERE ").append(whereClause); } if (orderBy.length() > 0) { query.append(" ORDER BY ").append(orderBy); } stmt = conn.prepareStatement(query.toString()); rs = stmt.executeQuery(); while (rs.next()) { attrs.clear(); final ResultSetMetaData rsMeta = rs.getMetaData(); for (int i = 0; i < rsMeta.getColumnCount(); i++) { final String columnName = rsMeta.getColumnName(i + 1); final Integer columnType = rsMeta.getColumnType(i + 1); // Retrieve value taking care of binary values. String value = getValues(rs, columnName, columnType); if (value != null && (!COLUMNS_TO_BE_NULLIFIED.containsKey(tableName) || !COLUMNS_TO_BE_NULLIFIED.get(tableName).contains(columnName))) { attrs.addAttribute("", "", columnName, "CDATA", value); } } handler.startElement("", "", tableName, attrs); handler.endElement("", "", tableName); LOG.debug("Add record {}", attrs); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("While closing result set", e); } } if (pkeyRS != null) { try { pkeyRS.close(); } catch (SQLException e) { LOG.error("While closing result set", e); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { LOG.error("While closing result set", e); } } } }
From source file:com.jbrisbin.vpc.jobsched.sql.SqlMessageHandler.java
public SqlMessage handleMessage(final SqlMessage msg) throws Exception { log.debug("handling message: " + msg.toString()); DataSource ds = appCtx.getBean(msg.getDatasource(), DataSource.class); JdbcTemplate tmpl = new JdbcTemplate(ds); String sql = msg.getSql();// w ww . jav a 2s .c om CallableStatementCreator stmtCreator = null; CallableStatementCallback<SqlMessage> callback = null; if (sql.startsWith("plugin:")) { // Use a plugin to get the sql String pluginName = (sql.contains("?") ? sql.substring(7, sql.indexOf('?')) : sql.substring(7)); final Plugin plugin = groovyPluginManager.getPlugin(pluginName); Map<String, Object> vars = new LinkedHashMap<String, Object>(); vars.put("message", msg); vars.put("datasource", ds); vars.put("listen", groovyClosureFactory.createListenClosure(msg)); vars.put("mapreduce", groovyClosureFactory.createMapReduceClosure(msg)); plugin.setContext(vars); // Execute this plugin plugin.run(); Object o = plugin.get("sql"); if (null != o && o instanceof Closure) { sql = ((Closure) o).call(msg).toString(); } else if (o instanceof String || o instanceof GString) { sql = o.toString(); } else { throw new IllegalStateException("Can't convert " + String.valueOf(o) + " to SQL statement."); } msg.setSql(sql); o = plugin.get("statementCreator"); if (null != o && o instanceof Closure) { stmtCreator = new CallableStatementCreator() { public CallableStatement createCallableStatement(Connection con) throws SQLException { Object obj = ((Closure) plugin.get("statementCreator")).call(new Object[] { con, msg }); log.debug("from plugin statementCreator: " + String.valueOf(obj)); return (CallableStatement) obj; } }; } else { throw new IllegalStateException("Can't convert " + String.valueOf(o) + " to CallableStatementCreator. Define a closure named 'statementCreator' in your plugin."); } o = plugin.get("callback"); if (null != o && o instanceof Closure) { callback = new CallableStatementCallback<SqlMessage>() { public SqlMessage doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException { Object obj = ((Closure) plugin.get("callback")).call(new Object[] { cs, msg }); log.debug("from plugin callback: " + String.valueOf(obj)); return (SqlMessage) obj; } }; } else { throw new IllegalStateException("Can't convert " + String.valueOf(o) + " to CallableStatementCallback. Define a closure named 'callback' in your plugin."); } } else { stmtCreator = new CallableStatementCreator() { public CallableStatement createCallableStatement(Connection connection) throws SQLException { CallableStatement stmt = connection.prepareCall(msg.getSql()); List<Object> params = msg.getParams(); if (null != params) { int index = 1; for (Object obj : params) { stmt.setObject(index++, obj); } } return stmt; } }; callback = new CallableStatementCallback<SqlMessage>() { public SqlMessage doInCallableStatement(CallableStatement callableStatement) throws SQLException, DataAccessException { if (null == msg.getResults().getData()) { msg.getResults().setData(new ArrayList<List<Object>>()); } if (callableStatement.execute()) { ResultSet results = callableStatement.getResultSet(); // Pull out column names ResultSetMetaData meta = results.getMetaData(); String[] columns = new String[meta.getColumnCount()]; for (int i = 1; i <= meta.getColumnCount(); i++) { columns[i - 1] = meta.getColumnName(i); } msg.getResults().getColumnNames().addAll(Arrays.asList(columns)); int total = 0; while (results.next()) { List<Object> row = new ArrayList<Object>(columns.length); for (int i = 1; i <= columns.length; i++) { row.add(results.getObject(i)); } msg.getResults().getData().add(row); total++; } msg.getResults().setTotalRows(total); } else { msg.getResults().getColumnNames().add("updateCount"); msg.getResults().setTotalRows(1); List<Object> updCnt = new ArrayList<Object>(1); updCnt.add(callableStatement.getUpdateCount()); msg.getResults().getData().add(updCnt); } return msg; } }; } try { tmpl.setExceptionTranslator(appCtx.getBean(SQLExceptionTranslator.class)); } catch (NoSuchBeanDefinitionException notfound) { // IGNORED } if (null != stmtCreator && null != callback) { try { tmpl.execute(stmtCreator, callback); } catch (Throwable t) { log.error(t.getMessage(), t); List<String> errors = new ArrayList<String>(); errors.add(t.getMessage()); Throwable cause = t.getCause(); if (null != cause) { do { errors.add(cause.getMessage()); } while (null != (cause = cause.getCause())); } msg.getResults().setErrors(errors); } } else { log.warn("CallableStatementCreator and/or CallableStatementCallback where empty. " + "Make sure your plugin provides these under 'statementCreator' and 'callback' respectively."); } return msg; }
From source file:orca.util.db.MySqlBase.java
/** * Create a Properties list from a ResultSet obtained from a query * @param rs The ResultSet//from w ww . j a v a 2s. c om * @param type Object type (node, machine, etc) * @return Translated properties list * @throws Exception in case of error */ protected Vector<Properties> createSearchResultsTyped(ResultSet rs, String type) throws Exception { Vector<Properties> result = new Vector<Properties>(); ResultSetMetaData rsm = rs.getMetaData(); int numberOfCols = rsm.getColumnCount(); String[] Columns = new String[numberOfCols]; for (int i = 0; i < numberOfCols; i++) { Columns[i] = rsm.getColumnName(i + 1); } while (rs.next()) { Properties p = new Properties(); for (int i = 0; i < numberOfCols; i++) { String tmp = rs.getString(i + 1); if (tmp != null) { p.put(Columns[i], tmp); } } Properties set = mapper.mysqlToJava(type, p); result.add(set); } return result; }
From source file:org.b3log.latke.repository.jdbc.util.JdbcUtil.java
/** * resultSetToJsonObject.// w w w . ja va 2 s . c o m * * @param resultSet resultSet * @param ifOnlyOne ifOnlyOne * @param tableName tableName * * @return JSONObject * @throws SQLException SQLException * @throws JSONException JSONException * @throws RepositoryException RepositoryException */ private static JSONObject resultSetToJsonObject(final ResultSet resultSet, final boolean ifOnlyOne, final String tableName) throws SQLException, JSONException, RepositoryException { final ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); final List<FieldDefinition> definitioList = JdbcRepositories.getRepositoriesMap().get(tableName); if (definitioList == null) { LOGGER.log(Level.SEVERE, "resultSetToJsonObject: null definitioList finded for table {0}", tableName); throw new RepositoryException( "resultSetToJsonObject: null definitioList finded for table " + tableName); } final Map<String, FieldDefinition> dMap = new HashMap<String, FieldDefinition>(); for (FieldDefinition fieldDefinition : definitioList) { if (RuntimeDatabase.H2 == Latkes.getRuntimeDatabase()) { dMap.put(fieldDefinition.getName().toUpperCase(), fieldDefinition); } else { dMap.put(fieldDefinition.getName(), fieldDefinition); } } final int numColumns = resultSetMetaData.getColumnCount(); final JSONArray jsonArray = new JSONArray(); JSONObject jsonObject; String columnName; while (resultSet.next()) { jsonObject = new JSONObject(); for (int i = 1; i < numColumns + 1; i++) { columnName = resultSetMetaData.getColumnName(i); final FieldDefinition definition = dMap.get(columnName); if (definition == null) { // COUNT(OID) jsonObject.put(columnName, resultSet.getObject(columnName)); } else { if ("boolean".equals(definition.getType())) { jsonObject.put(definition.getName(), resultSet.getBoolean(columnName)); } else { final Object v = resultSet.getObject(columnName); while (true) { if (RuntimeDatabase.H2 != Latkes.getRuntimeDatabase()) { jsonObject.put(definition.getName(), v); break; } // H2 if ("String".equals(definition.getType()) && v instanceof Clob) { // H2 CLOB final Clob clob = (Clob) v; String str = null; try { str = IOUtils.toString(clob.getCharacterStream()); } catch (final IOException e) { LOGGER.log(Level.SEVERE, "Cant not read column[name=" + columnName + "] in table[name=" + tableName + "] on H2", e); } finally { clob.free(); } jsonObject.put(definition.getName(), str); break; } // H2 other types jsonObject.put(definition.getName(), v); break; } } } } jsonArray.put(jsonObject); } if (ifOnlyOne) { if (jsonArray.length() > 0) { jsonObject = jsonArray.getJSONObject(0); return jsonObject; } return null; } jsonObject = new JSONObject(); jsonObject.put(Keys.RESULTS, jsonArray); return jsonObject; }
From source file:com.datatorrent.contrib.enrichment.JDBCLoader.java
protected ArrayList<Object> getDataFrmResult(Object result) throws RuntimeException { try {/*w ww. j a va 2 s . c o m*/ ResultSet resultSet = (ResultSet) result; if (resultSet.next()) { ResultSetMetaData rsdata = resultSet.getMetaData(); // If the includefields is empty, populate it from ResultSetMetaData if (CollectionUtils.isEmpty(includeFields)) { if (includeFields == null) { includeFields = new ArrayList<String>(); } for (int i = 1; i <= rsdata.getColumnCount(); i++) { includeFields.add(rsdata.getColumnName(i)); } } ArrayList<Object> res = new ArrayList<Object>(); for (String f : includeFields) { res.add(resultSet.getObject(f)); } return res; } else { return null; } } catch (SQLException e) { throw new RuntimeException(e); } }
From source file:io.lightlink.oracle.AbstractOracleType.java
protected STRUCT createStruct(Connection con, Object value, String type) throws SQLException { if (value == null) return null; Map mapValue;/*from w w w .j a va2s. c o m*/ if (value instanceof Map) { mapValue = (Map) value; mapValue = new CaseInsensitiveMap(mapValue); } else { // create a Map from bean Map map = new CaseInsensitiveMap(new BeanMap(value)); map.remove("class"); mapValue = map; } STRUCT struct; StructDescriptor structType = safeCreateStructureDescriptor(type, con); ResultSetMetaData stuctMeteData = structType.getMetaData(); List<Object> orderedValues = new ArrayList<Object>(); if (stuctMeteData.getColumnCount() == 1 && mapValue.size() == 1) { orderedValues.add(mapValue.values().iterator().next()); } else { for (int col = 1; col <= stuctMeteData.getColumnCount(); col++) { Object v = mapValue.get(stuctMeteData.getColumnName(col)); if (v == null) { v = mapValue.get(stuctMeteData.getColumnName(col).replaceAll("_", "")); } String typeName = stuctMeteData.getColumnTypeName(col); int columnType = stuctMeteData.getColumnType(col); if (columnType == OracleTypes.ARRAY) { v = createArray(con, v, typeName); } else if (columnType == OracleTypes.JAVA_STRUCT || columnType == OracleTypes.JAVA_OBJECT || columnType == OracleTypes.STRUCT) { v = createStruct(con, v, typeName); } orderedValues.add(v); } } Object[] values = orderedValues.toArray(); for (int j = 0; j < values.length; j++) { Object v = values[j]; if (v instanceof Long && stuctMeteData.getColumnTypeName(j + 1).equalsIgnoreCase("TIMESTAMP")) { values[j] = new Timestamp((Long) v); } else if (v instanceof Long && stuctMeteData.getColumnTypeName(j + 1).equalsIgnoreCase("DATE")) { values[j] = new Date((Long) v); } } struct = new STRUCT(structType, con, values); return struct; }
From source file:jp.primecloud.auto.tool.management.db.SQLExecuter.java
public List<List<Object>> showColumn(String sql) throws SQLException, Exception { Connection con = null;/*w w w . ja va 2s. c o m*/ Statement stmt = null; ResultSet rs = null; log.info("[" + sql + "] ???"); List<List<Object>> results = new ArrayList<List<Object>>(); try { con = dbConnector.getConnection(); stmt = con.createStatement(); rs = stmt.executeQuery(sql); ResultSetMetaData rsMetaData = rs.getMetaData(); int size = rsMetaData.getColumnCount(); List<Object> columnNames = new ArrayList<Object>(); for (int n = 1; n <= size; n++) { columnNames.add(rsMetaData.getColumnName(n)); } results.add(columnNames); while (rs.next()) { List<Object> columns = new ArrayList<Object>(); for (int i = 1; i <= size; i++) { columns.add(rs.getObject(i)); } results.add(columns); } log.info("[" + sql + "] ????"); } catch (SQLException e) { log.error(e.getMessage(), e); throw new SQLException(e); } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception(e); } finally { try { dbConnector.closeConnection(con, stmt, rs); } catch (Exception e) { e.printStackTrace(); } } return results; }
From source file:org.apache.calcite.avatica.jdbc.JdbcMeta.java
/** * Convert from JDBC metadata to Avatica columns. *//*from ww w .j av a 2s. co 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.mirth.connect.connectors.jdbc.JdbcConnectorService.java
public Object invoke(String method, Object object, String sessionsId) throws Exception { if (method.equals("getInformationSchema")) { // method 'getInformationSchema' will return Set<Table> Connection connection = null; try {// ww w. ja v a 2 s . c om Properties properties = (Properties) object; String driver = properties.getProperty(DatabaseReaderProperties.DATABASE_DRIVER); String address = properties.getProperty(DatabaseReaderProperties.DATABASE_URL); String user = properties.getProperty(DatabaseReaderProperties.DATABASE_USERNAME); String password = properties.getProperty(DatabaseReaderProperties.DATABASE_PASSWORD); // Although these properties are not persisted, they used by the JdbcConnectorService String tableNamePatternExp = properties .getProperty(DatabaseReaderProperties.DATABASE_TABLE_NAME_PATTERN_EXPRESSION); String selectLimit = properties.getProperty(DatabaseReaderProperties.DATABASE_SELECT_LIMIT); String schema = null; Class.forName(driver); int oldLoginTimeout = DriverManager.getLoginTimeout(); DriverManager.setLoginTimeout(30); connection = DriverManager.getConnection(address, user, password); DriverManager.setLoginTimeout(oldLoginTimeout); DatabaseMetaData dbMetaData = connection.getMetaData(); // the sorted set to hold the table information SortedSet<Table> tableInfoList = new TreeSet<Table>(); // Use a schema if the user name matches one of the schemas. // Fix for Oracle: MIRTH-1045 ResultSet schemasResult = null; try { schemasResult = dbMetaData.getSchemas(); while (schemasResult.next()) { String schemaResult = schemasResult.getString(1); if (user.equalsIgnoreCase(schemaResult)) { schema = schemaResult; } } } finally { if (schemasResult != null) { schemasResult.close(); } } // based on the table name pattern, attempt to retrieve the table information List<String> tablePatternList = translateTableNamePatternExpression(tableNamePatternExp); List<String> tableNameList = new ArrayList<String>(); // go through each possible table name patterns and query for the tables for (String tableNamePattern : tablePatternList) { ResultSet rs = null; try { rs = dbMetaData.getTables(null, schema, tableNamePattern, TABLE_TYPES); // based on the result set, loop through to store the table name so it can be used to // retrieve the table's column information while (rs.next()) { tableNameList.add(rs.getString("TABLE_NAME")); } } finally { if (rs != null) { rs.close(); } } } // for each table, grab their column information for (String tableName : tableNameList) { ResultSet rs = null; ResultSet backupRs = null; boolean fallback = false; try { // apparently it's much more efficient to use ResultSetMetaData to retrieve // column information. So each driver is defined with their own unique SELECT // statement to query the table columns and use ResultSetMetaData to retrieve // the column information. If driver is not defined with the select statement // then we'll define to the generic method of getting column information, but // this could be extremely slow List<Column> columnList = new ArrayList<Column>(); if (StringUtils.isEmpty(selectLimit)) { logger.debug("No select limit is defined, using generic method"); rs = dbMetaData.getColumns(null, null, tableName, null); // retrieve all relevant column information for (int i = 0; rs.next(); i++) { Column column = new Column(rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"), rs.getInt("COLUMN_SIZE")); columnList.add(column); } } else { logger.debug( "Select limit is defined, using specific select query : '" + selectLimit + "'"); // replace the '?' with the appropriate schema.table name, and use ResultSetMetaData to // retrieve column information final String schemaTableName = StringUtils.isNotEmpty(schema) ? schema + "." + tableName : tableName; final String queryString = selectLimit.trim().replaceAll("\\?", schemaTableName); Statement statement = connection.createStatement(); try { rs = statement.executeQuery(queryString); ResultSetMetaData rsmd = rs.getMetaData(); // retrieve all relevant column information for (int i = 1; i < rsmd.getColumnCount() + 1; i++) { Column column = new Column(rsmd.getColumnName(i), rsmd.getColumnTypeName(i), rsmd.getPrecision(i)); columnList.add(column); } } catch (SQLException sqle) { logger.info("Failed to execute '" + queryString + "', fall back to generic approach to retrieve column information"); fallback = true; } finally { if (statement != null) { statement.close(); } } // failed to use selectLimit method, so we need to fall back to generic // if this generic approach fails, then there's nothing we can do if (fallback) { // Re-initialize in case some columns were added before failing columnList = new ArrayList<Column>(); logger.debug("Using fallback method for retrieving columns"); backupRs = dbMetaData.getColumns(null, null, tableName, null); // retrieve all relevant column information for (int i = 0; backupRs.next(); i++) { Column column = new Column(backupRs.getString("COLUMN_NAME"), backupRs.getString("TYPE_NAME"), backupRs.getInt("COLUMN_SIZE")); columnList.add(column); } } } // create table object and add to the list of table definitions Table table = new Table(tableName, columnList); tableInfoList.add(table); } finally { if (rs != null) { rs.close(); } if (backupRs != null) { backupRs.close(); } } } return tableInfoList; } catch (Exception e) { throw new Exception("Could not retrieve database tables and columns.", e); } finally { if (connection != null) { connection.close(); } } } return null; }