List of usage examples for java.sql ResultSetMetaData getColumnLabel
String getColumnLabel(int column) throws SQLException;
From source file:org.guzz.orm.mapping.FormBeanRowDataLoader.java
public Object rs2Object(ObjectMapping mapping, ResultSet rs) throws SQLException { ResultSetMetaData meta = rs.getMetaData(); int count = meta.getColumnCount(); Object obj = BeanCreator.newBeanInstance(this.beanCls); if (this.customTableView != null) { mapping = this.customTableView.getRuntimeObjectMapping(Guzz.getTableCondition()); } else if (this.colsMapping != null) { mapping = this.colsMapping; }/*from w w w . ja v a2 s.co m*/ if (isMap) { for (int i = 1; i <= count; i++) { String colName = meta.getColumnLabel(i); TableColumn tc = mapping.getTable().getColumnByColNameInRS(colName); Object value = null; if (tc != null) { value = tc.getOrm().loadResult(rs, obj, i); } else { value = rs.getObject(i); } ((Map) obj).put(tc == null ? colName : tc.getPropName(), value); } } else { for (int i = 1; i <= count; i++) { String colName = meta.getColumnLabel(i); TableColumn tc = mapping.getTable().getColumnByColNameInRS(colName); String propName = null; Object value = null; if (tc != null) { propName = tc.getPropName(); value = tc.getOrm().loadResult(rs, obj, i); } else { propName = (String) this.writableProps.get(colName.toLowerCase()); SQLDataType type = (SQLDataType) cachedDataTypes.get(propName); if (type != null) { value = type.getSQLValue(rs, i); } else { String propType = this.beanWrapper.getPropertyTypeName(propName); type = mapping.getDbGroup().getDialect().getDataType(propType); value = type.getSQLValue(rs, i); cachedDataTypes.put(propName, type); } } if (propName == null) { if (log.isWarnEnabled()) { log.warn("rs column:[" + colName + "] cann't be mapped to java class:[" + this.beanCls.getName() + "]. The column is not writable."); } continue; } this.beanWrapper.setValue(obj, propName, value); } } return obj; }
From source file:org.apache.nifi.processors.standard.util.JdbcCommon.java
/** * Creates an Avro schema from a result set. If the table/record name is known a priori and provided, use that as a * fallback for the record name if it cannot be retrieved from the result set, and finally fall back to a default value. * * @param rs The result set to convert to Avro * @param recordName The a priori record name to use if it cannot be determined from the result set. * @return A Schema object representing the result set converted to an Avro record * @throws SQLException if any error occurs during conversion *//* w ww . ja va 2 s . c o m*/ public static Schema createSchema(final ResultSet rs, String recordName, boolean convertNames) throws SQLException { final ResultSetMetaData meta = rs.getMetaData(); final int nrOfColumns = meta.getColumnCount(); String tableName = StringUtils.isEmpty(recordName) ? "NiFi_ExecuteSQL_Record" : recordName; if (nrOfColumns > 0) { String tableNameFromMeta = meta.getTableName(1); if (!StringUtils.isBlank(tableNameFromMeta)) { tableName = tableNameFromMeta; } } if (convertNames) { tableName = normalizeNameForAvro(tableName); } final FieldAssembler<Schema> builder = SchemaBuilder.record(tableName).namespace("any.data").fields(); /** * Some missing Avro types - Decimal, Date types. May need some additional work. */ for (int i = 1; i <= nrOfColumns; i++) { /** * as per jdbc 4 specs, getColumnLabel will have the alias for the column, if not it will have the column name. * so it may be a better option to check for columnlabel first and if in case it is null is someimplementation, * check for alias. Postgres is the one that has the null column names for calculated fields. */ String nameOrLabel = StringUtils.isNotEmpty(meta.getColumnLabel(i)) ? meta.getColumnLabel(i) : meta.getColumnName(i); String columnName = convertNames ? normalizeNameForAvro(nameOrLabel) : nameOrLabel; switch (meta.getColumnType(i)) { case CHAR: case LONGNVARCHAR: case LONGVARCHAR: case NCHAR: case NVARCHAR: case VARCHAR: case CLOB: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); break; case BIT: case BOOLEAN: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().booleanType().endUnion() .noDefault(); break; case INTEGER: if (meta.isSigned(i) || (meta.getPrecision(i) > 0 && meta.getPrecision(i) <= MAX_DIGITS_IN_INT)) { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion() .noDefault(); } else { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType().endUnion() .noDefault(); } break; case SMALLINT: case TINYINT: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion() .noDefault(); break; case BIGINT: // Check the precision of the BIGINT. Some databases allow arbitrary precision (> 19), but Avro won't handle that. // If the precision > 19 (or is negative), use a string for the type, otherwise use a long. The object(s) will be converted // to strings as necessary int precision = meta.getPrecision(i); if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); } else { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType().endUnion() .noDefault(); } break; // java.sql.RowId is interface, is seems to be database // implementation specific, let's convert to String case ROWID: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); break; case FLOAT: case REAL: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().floatType().endUnion() .noDefault(); break; case DOUBLE: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().doubleType().endUnion() .noDefault(); break; // Did not find direct suitable type, need to be clarified!!!! case DECIMAL: case NUMERIC: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); break; // Did not find direct suitable type, need to be clarified!!!! case DATE: case TIME: case TIMESTAMP: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); break; case BINARY: case VARBINARY: case LONGVARBINARY: case ARRAY: case BLOB: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().bytesType().endUnion() .noDefault(); break; default: throw new IllegalArgumentException("createSchema: Unknown SQL type " + meta.getColumnType(i) + " / " + meta.getColumnTypeName(i) + " (table: " + tableName + ", column: " + columnName + ") cannot be converted to Avro type"); } } return builder.endRecord(); }
From source file:be.dataminded.nifi.plugins.util.JdbcCommon.java
/** * Creates an Avro schema from a result set. If the table/record name is known a priori and provided, use that as a * fallback for the record name if it cannot be retrieved from the result set, and finally fall back to a default value. * * @param rs The result set to convert to Avro * @param recordName The a priori record name to use if it cannot be determined from the result set. * @return A Schema object representing the result set converted to an Avro record * @throws SQLException if any error occurs during conversion *//* ww w . j a va 2 s. c o m*/ public static Schema createSchema(final ResultSet rs, String recordName, boolean convertNames) throws SQLException { final ResultSetMetaData meta = rs.getMetaData(); final int nrOfColumns = meta.getColumnCount(); String tableName = StringUtils.isEmpty(recordName) ? "NiFi_ExecuteSQL_Record" : recordName; if (nrOfColumns > 0) { String tableNameFromMeta = meta.getTableName(1); if (!StringUtils.isBlank(tableNameFromMeta)) { tableName = tableNameFromMeta; } } if (convertNames) { tableName = normalizeNameForAvro(tableName); } final FieldAssembler<Schema> builder = SchemaBuilder.record(tableName).namespace("any.data").fields(); /** * Some missing Avro types - Decimal, Date types. May need some additional work. */ for (int i = 1; i <= nrOfColumns; i++) { /** * as per jdbc 4 specs, getColumnLabel will have the alias for the column, if not it will have the column name. * so it may be a better option to check for columnlabel first and if in case it is null is someimplementation, * check for alias. Postgres is the one that has the null column names for calculated fields. */ String nameOrLabel = StringUtils.isNotEmpty(meta.getColumnLabel(i)) ? meta.getColumnLabel(i) : meta.getColumnName(i); String columnName = convertNames ? normalizeNameForAvro(nameOrLabel) : nameOrLabel; switch (meta.getColumnType(i)) { case CHAR: case LONGNVARCHAR: case LONGVARCHAR: case NCHAR: case NVARCHAR: case VARCHAR: case CLOB: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); break; case BIT: case BOOLEAN: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().booleanType().endUnion() .noDefault(); break; case INTEGER: if (meta.isSigned(i)) { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion() .noDefault(); } else { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType().endUnion() .noDefault(); } break; case SMALLINT: case TINYINT: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion() .noDefault(); break; case BIGINT: // Check the precision of the BIGINT. Some databases allow arbitrary precision (> 19), but Avro won't handle that. // If the precision > 19 (or is negative), use a string for the type, otherwise use a long. The object(s) will be converted // to strings as necessary int precision = meta.getPrecision(i); if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); } else { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType().endUnion() .noDefault(); } break; // java.sql.RowId is interface, is seems to be database // implementation specific, let's convert to String case ROWID: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); break; case FLOAT: case REAL: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().floatType().endUnion() .noDefault(); break; case DOUBLE: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().doubleType().endUnion() .noDefault(); break; // Did not find direct suitable type, need to be clarified!!!! case DECIMAL: case NUMERIC: int scale = meta.getScale(i); if (scale == 0) { if (meta.getPrecision(i) < 10) { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion() .noDefault(); } else { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType() .endUnion().noDefault(); } } else { builder.name(columnName).type().unionOf().nullBuilder().endNull().and().doubleType().endUnion() .noDefault(); } break; // Did not find direct suitable type, need to be clarified!!!! case DATE: case TIME: case TIMESTAMP: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion() .noDefault(); break; case BINARY: case VARBINARY: case LONGVARBINARY: case ARRAY: case BLOB: builder.name(columnName).type().unionOf().nullBuilder().endNull().and().bytesType().endUnion() .noDefault(); break; default: throw new IllegalArgumentException("createSchema: Unknown SQL type " + meta.getColumnType(i) + " cannot be converted to Avro type"); } } return builder.endRecord(); }
From source file:com.xpfriend.fixture.cast.temp.Database.java
private String getColumnLabel(ResultSetMetaData md, int column) throws SQLException { try {// w w w.ja v a2 s .com String label = md.getColumnLabel(column); if (!Strings.isEmpty(label)) { return label; } } catch (Exception e) { ExceptionHandler.ignore(e); } return md.getColumnName(column); }
From source file:servlet.CinemaControl.java
protected void doListSeats(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); ServletContext sc = getServletContext(); String db_driver = sc.getInitParameter("db_driver"), db_url = sc.getInitParameter("db_url"), db_user = sc.getInitParameter("db_user"), db_password = sc.getInitParameter("db_password"); String db_q_cinemas = "SELECT * FROM Cinema;"; String db_q_houses = "SELECT * FROM House WHERE cinemaID = ?;"; String db_q_seats = "SELECT * FROM Seat WHERE houseID = ?;"; try {//from ww w. j a v a 2 s .c o m JSONObject jso0 = new JSONObject(); JSONArray jsa0 = new JSONArray(); jso0.put("cinemas", jsa0); Class.forName(db_driver); Connection conn = DriverManager.getConnection(db_url, db_user, db_password); Statement statmt1 = conn.createStatement(); ResultSet rs1 = statmt1.executeQuery(db_q_cinemas); ResultSetMetaData rsmd1 = rs1.getMetaData(); int numOfColumns1 = rsmd1.getColumnCount(); while (rs1.next()) { JSONObject jso1 = new JSONObject(); jsa0.put(jso1); for (int i = 1; i <= numOfColumns1; i++) { jso1.put(rsmd1.getColumnLabel(i), rs1.getString(i)); } int cinemaID = Integer.parseInt(jso1.getString("cinemaID")); JSONArray jsa1 = new JSONArray(); jso1.put("houses", jsa1); PreparedStatement statmt2 = conn.prepareStatement(db_q_houses); statmt2.setInt(1, cinemaID); if (statmt2.execute()) { ResultSet rs2 = statmt2.getResultSet(); ResultSetMetaData rsmd2 = rs2.getMetaData(); int numOfColumns2 = rsmd2.getColumnCount(); while (rs2.next()) { JSONObject jso2 = new JSONObject(); jsa1.put(jso2); for (int j = 1; j <= numOfColumns2; j++) { jso2.put(rsmd2.getColumnLabel(j), rs2.getString(j)); } int houseID = Integer.parseInt(jso2.getString("houseID")); JSONArray jsa2 = new JSONArray(); jso2.put("seats", jsa2); PreparedStatement statmt3 = conn.prepareStatement(db_q_seats); statmt3.setInt(1, houseID); if (statmt3.execute()) { ResultSet rs3 = statmt3.getResultSet(); ResultSetMetaData rsmd3 = rs3.getMetaData(); int numOfColumns3 = rsmd3.getColumnCount(); while (rs3.next()) { JSONObject jso3 = new JSONObject(); jsa2.put(jso3); for (int k = 1; k <= numOfColumns3; k++) { jso3.put(rsmd3.getColumnLabel(k), rs3.getString(k)); } } } } } } out.println(jso0.toString()); } catch (ClassNotFoundException ex) { Logger.getLogger(CinemaControl.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(CinemaControl.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { Logger.getLogger(CinemaControl.class.getName()).log(Level.SEVERE, null, ex); } }
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.jav a 2s. 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:org.apache.sqoop.connector.hbase.HbaseFromInitializer.java
@Override public Schema getSchema(InitializerContext context, LinkConfiguration linkConfig, FromJobConfiguration fromJobConfig) { executor = new HbaseExecutor(linkConfig.linkConfig); String schemaName = fromJobConfig.fromJobConfig.tableName; if (schemaName == null) { schemaName = "Query"; } else if (fromJobConfig.fromJobConfig.schemaName != null) { schemaName = fromJobConfig.fromJobConfig.schemaName + "." + schemaName; }//from w w w . j a v a2 s . c om Schema schema = new Schema(schemaName); ResultSet rs = null; ResultSetMetaData rsmt = null; try { rs = executor.executeQuery(context.getString(HbaseConnectorConstants.CONNECTOR_JDBC_FROM_DATA_SQL) .replace(HbaseConnectorConstants.SQL_CONDITIONS_TOKEN, "1 = 0")); rsmt = rs.getMetaData(); for (int i = 1; i <= rsmt.getColumnCount(); i++) { String columnName = rsmt.getColumnLabel(i); if (StringUtils.isEmpty(columnName)) { columnName = rsmt.getColumnName(i); if (StringUtils.isEmpty(columnName)) { columnName = "Column " + i; } } Column column = SqlTypesUtils.sqlTypeToSchemaType(rsmt.getColumnType(i), columnName, rsmt.getPrecision(i), rsmt.getScale(i)); 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); } } if (executor != null) { executor.close(); } } }
From source file:org.hsweb.ezorm.rdb.executor.AbstractJdbcSqlExecutor.java
@Override public <T> List<T> list(SQL sql, ObjectWrapper<T> wrapper) throws SQLException { if (sql instanceof EmptySQL) return new ArrayList<>(); //sql??sql/* w ww. j a v a2 s . c o m*/ SQLInfo info = compileSql(sql); printSql(info);//?sql? Connection connection = getConnection(); PreparedStatement statement = null; ResultSet resultSet = null; List<T> datas = new ArrayList<>(); try { //SQL statement = connection.prepareStatement(info.getSql()); this.preparedParam(statement, info); //sql resultSet = statement.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int count = metaData.getColumnCount(); //?sql?? List<String> headers = new ArrayList<>(); for (int i = 1; i <= count; i++) { headers.add(metaData.getColumnLabel(i)); } wrapper.setUp(headers); int index = 0; while (resultSet.next()) { //, T data = wrapper.newInstance(); for (int i = 0; i < headers.size(); i++) { Object value = resultSet.getObject(i + 1); wrapper.wrapper(data, index, headers.get(i), value); } index++; wrapper.done(data); datas.add(data); } if (logger.isDebugEnabled()) { logger.debug("<== total: {}", index); } } finally { closeResultSet(resultSet); closeStatement(statement); //?JDBC releaseConnection(connection); } return datas; }
From source file:org.vivoweb.harvester.util.CSVtoJDBC.java
/** * Move CSV data into a recordHandler//from ww w.ja v a 2s.c o m * @throws IOException error reading from database or file */ public void execute() throws IOException { try { ResultSet rs = Csv.getInstance().read(new InputStreamReader(this.csvStream), null); ResultSetMetaData meta = rs.getMetaData(); Statement cursor = this.output.createStatement(); int rowID = 0; StringBuilder createTable = new StringBuilder("CREATE TABLE "); createTable.append(this.tableName); createTable.append("( ROWID int NOT NULL, "); this.fieldNames.add("ROWID"); StringBuilder columnNames = new StringBuilder("( ROWID, "); for (int i = 0; i < meta.getColumnCount(); i++) { String colLbl = meta.getColumnLabel(i + 1); createTable.append("\n"); createTable.append(colLbl); this.fieldNames.add(colLbl); createTable.append((i == (meta.getColumnCount() - 1)) ? " TEXT )" : " TEXT ,"); columnNames.append(colLbl); columnNames.append((i == (meta.getColumnCount() - 1)) ? " )" : ", "); } log.debug("Create table command: \n" + createTable.toString()); cursor.execute(createTable.toString()); cursor.execute("ALTER TABLE " + this.tableName + " ADD PRIMARY KEY (ROWID)"); while (rs.next()) { StringBuilder insertCommand = new StringBuilder("INSERT INTO "); insertCommand.append(this.tableName); insertCommand.append(" "); insertCommand.append(columnNames.toString()); insertCommand.append("\nVALUES ("); insertCommand.append(rowID); insertCommand.append(", '"); for (int i = 0; i < meta.getColumnCount(); i++) { insertCommand.append(rs.getString(i + 1)); insertCommand.append((i == (meta.getColumnCount() - 1)) ? "')" : "', '"); } log.debug("Insert command: \n" + insertCommand.toString()); cursor.executeUpdate(insertCommand.toString()); rowID++; } } catch (FileSystemException e) { throw new IOException(e); } catch (SQLException e) { throw new IOException(e); } }
From source file:com.tascape.reactor.report.MySqlBaseBean.java
public List<Map<String, Object>> dumpResultSetToList(ResultSet rs) throws SQLException { List<Map<String, Object>> rsml = new ArrayList<>(); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { Map<String, Object> d = new LinkedHashMap<>(); for (int col = 1; col <= rsmd.getColumnCount(); col++) { d.put(rsmd.getColumnLabel(col), rs.getObject(col)); }//from w ww . j a v a 2s . com rsml.add(d); } LOG.trace("{} rows loaded", rsml.size()); return rsml; }