List of usage examples for java.sql ResultSet getObject
Object getObject(String columnLabel) throws SQLException;
Gets the value of the designated column in the current row of this ResultSet
object as an Object
in the Java programming language.
From source file:com.jfinal.plugin.activerecord.Model.java
/** * Get id after save method./*w w w. j av a 2s.com*/ */ private void getGeneratedKey(PreparedStatement pst, TableInfo tableInfo) throws SQLException { String pKey = tableInfo.getPrimaryKey(); if (get(pKey) == null || DbKit.dialect.isOracle()) { ResultSet rs = pst.getGeneratedKeys(); if (rs.next()) { Class colType = tableInfo.getColType(pKey); if (colType == Integer.class || colType == int.class) set(pKey, rs.getInt(1)); else if (colType == Long.class || colType == long.class) set(pKey, rs.getLong(1)); else set(pKey, rs.getObject(1)); // It returns Long object for int colType rs.close(); } } }
From source file:edu.ku.brc.specify.dbsupport.cleanuptools.GeoCleanupFuzzySearch.java
/** * @param rs/*w ww . jav a 2 s. c o m*/ * @param rankId * @param earthId * @return * @throws SQLException */ private boolean buildDoc(final ResultSet rs, final int rankId, final int earthId) throws SQLException { rowData.clear(); for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { rowData.add(rs.getObject(i + 1)); } return buildDocInsert(rowData, rankId, earthId); }
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 .j av a 2 s .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:com.egt.ejb.toolkit.ToolKitUtils.java
public Map enumMap(String tabname) { Map map = newMap();//w ww .ja v a 2 s.c o m if (StringUtils.isNotBlank(tabname)) { String tabla = tabname.trim(); String numero = "numero_" + tabla; String codigo = tabla.equals("opcion_binaria") ? "codigo_opcion_si_no" : "codigo_" + tabla; String comando = "SELECT " + numero + ", " + codigo + " FROM " + tabla + " ORDER BY " + numero; String sql1 = comando; Object resultado1; ResultSet resultSet1 = null; Object objeto1; String objeto2; try { if (this.getSqlAgent().connected()) { resultado1 = this.getSqlAgent().executeQuery(sql1); if (resultado1 != null && resultado1 instanceof ResultSet) { resultSet1 = (ResultSet) resultado1; while (resultSet1.next()) { objeto1 = resultSet1.getObject(1); objeto2 = resultSet1.getString(2); if (objeto1 instanceof Integer && objeto2 instanceof String) { map.put(objeto1.toString(), getLowerCaseEnumOptionIdentifier(objeto2)); } } } } } catch (SQLException e) { // TLC.getBitacora().fatal(e); } finally { DB.close(resultSet1); } } return map; }
From source file:com.egt.ejb.toolkit.ToolKitUtils.java
public Map enumLabelsMap(String tabname) { Map map = newMap();/*from w ww .jav a 2 s. c o m*/ if (StringUtils.isNotBlank(tabname)) { String tabla = tabname.trim(); String numero = "numero_" + tabla; String codigo = tabla.equals("opcion_binaria") ? "codigo_opcion_si_no" : "codigo_" + tabla; String comando = "SELECT " + numero + ", " + codigo + " FROM " + tabla + " ORDER BY " + numero; String sql1 = comando; Object resultado1; ResultSet resultSet1 = null; Object objeto1; String objeto2; try { if (this.getSqlAgent().connected()) { resultado1 = this.getSqlAgent().executeQuery(sql1); if (resultado1 != null && resultado1 instanceof ResultSet) { resultSet1 = (ResultSet) resultado1; while (resultSet1.next()) { objeto1 = resultSet1.getObject(1); objeto2 = resultSet1.getString(2); if (objeto1 instanceof Integer && objeto2 instanceof String) { map.put(objeto1.toString(), objeto2); } } } } } catch (SQLException e) { // TLC.getBitacora().fatal(e); } finally { DB.close(resultSet1); } } return map; }
From source file:jp.mathes.databaseWiki.db.postgres.PostgresBackend.java
@Override public List<Row> executeQuery(final String user, final String password, final String db, final String query) throws BackendException { Statement st = null;//from w w w.ja v a 2 s .c o m Connection conn = null; ResultSet rs = null; List<Row> result = new LinkedList<Row>(); try { conn = this.connectToDB(user, password, db); st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); this.logString(query.trim(), user); rs = st.executeQuery(query.trim()); while (rs.next()) { Row row = new PostgresRow(); ResultSetMetaData metaData = rs.getMetaData(); for (int i = 1; i <= metaData.getColumnCount(); i++) { row.getFields().add(rs.getObject(i)); row.getFieldsByName().put(metaData.getColumnName(i), rs.getObject(i)); } result.add(row); } } catch (SQLException e) { throw new BackendException(e); } catch (ClassNotFoundException e) { throw new BackendException(e); } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(st); DbUtils.closeQuietly(conn); } return result; }
From source file:de.innovationgate.webgate.api.jdbc.custom.JDBCSource.java
public boolean insertContent(String folder, Object key, Object bean) throws WGBackendException { ResultSet resultSet = null;/*w w w .j a va 2 s . co m*/ try { // Gather all columns to set as values, including those keys that are set. Find out the key to generate, if present. Map allColumns = new HashMap(); Map valuesMap = (Map) bean; allColumns.putAll(valuesMap); String keyToGenerate = null; Map keyMap = (Map) key; Iterator keys = keyMap.keySet().iterator(); while (keys.hasNext()) { String keyName = (String) keys.next(); Object value = keyMap.get(keyName); if (value != null) { allColumns.put(keyName, value); } else { keyToGenerate = keyName; } } // Execute Statement PreparedStatement stmt = getInsertStatement(folder, allColumns); int rows = stmt.executeUpdate(); if (rows != 1) { throw new WGBackendException("Insert failed. Wrong number of inserted rows returned: " + rows); } if (keyToGenerate == null) { return true; } // Try to retrieve generated key and store it at the bean and the key map if (!stmt.getConnection().getMetaData().supportsGetGeneratedKeys()) { throw new WGBackendException( "Row was inserted but JDBC Driver does not support returning of generated keys. Usage of a table with generated key is not possible with this driver."); } ResultSet generatedKeys = stmt.getGeneratedKeys(); generatedKeys.first(); Object generatedKey = generatedKeys.getObject(1); valuesMap.put(keyToGenerate, generatedKey); keyMap.put(keyToGenerate, generatedKey); if (getConnection().getAutoCommit() == false) { getConnection().commit(); } return true; /*String whereClause = getWhereClause(folder, key); resultSet = getTableResultSet(folder, whereClause, true); if (resultSet != null) { startResultSet(resultSet); if (!resultSet.next()) { resultSet.moveToInsertRow(); pushRowData(resultSet, (Map) bean); resultSet.insertRow(); if (getConnection().getAutoCommit() == false) { getConnection().commit(); } return true; } else { throw new WGBackendException("The key '" + key + "' already exists in table '" + folder + "'"); } } else { return false; }*/ } catch (SQLException e) { try { if (getConnection().getAutoCommit() == false) { getConnection().rollback(); } } catch (SQLException e1) { Logger.getLogger(LOGGER_NAME).error("Error rolling back content insertion", e); } throw new WGBackendException("Error inserting row", e); } finally { closeResultSet(resultSet); } }
From source file:mil.army.usace.data.nativequery.rdbms.NativeRdbmsQuery.java
private GeneratedKey insertWithGeneratedKeyReturn(Object record, boolean useDeclaredOnly) { PreparedStatement st = null;//from w ww . j a v a 2s . c o m boolean inTrans = inTransaction(); String command = null; int batchCount = 0; GeneratedKey gk = null; if (!inTrans) startTransaction(); try { Class objClass = record.getClass(); String schema = getEntitySchema(objClass); Boolean isCamelCased = useCamelCase(objClass); HashMap<Method, String> fieldMapping = getFieldMapping(objClass, GET, isCamelCased, useDeclaredOnly); String idFieldName = getIdFieldName(fieldMapping); HashMap<Integer, Method> indexMapping = new HashMap(); String tableName = getTableName(objClass); if (tableName == null) tableName = getDbName(isCamelCased, objClass.getSimpleName(), null); command = getInsertCommand(tableName, schema, fieldMapping, indexMapping); if (idFieldName != null) { st = conn.prepareStatement(command, new String[] { idFieldName }); } else { st = conn.prepareStatement(command); } for (int index : indexMapping.keySet()) { Object value = indexMapping.get(index).invoke(record, null); if (value instanceof java.util.Date) { value = new java.sql.Date(((java.util.Date) value).getTime()); } st.setObject((Integer) index, value); } st.execute(); ResultSet rs = st.getGeneratedKeys(); if (rs.next()) { gk = new GeneratedKey(idFieldName, rs.getObject(1)); } if (!inTrans) commitTransaction(); return gk; } catch (Exception ex) { ex.printStackTrace(); if (!inTrans) rollbackTransaction(); throw new NativeQueryException(command, "insertWithGeneratedKeyReturn", ex); } finally { if (st != null) { try { st.close(); } catch (Exception ex) { } } } }
From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public Map query(String sql, Object[] params) { final Map map = new HashMap(); List lstValue = new ArrayList(); map.put(KEY_VALUES, lstValue);//from w ww .ja v a 2s .c o m logger.debug(sql); getJdbcTemplate().query(sql, params, new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { map.put(KEY_META, rs.getMetaData()); int columnSize = rs.getMetaData().getColumnCount(); List lstField = new ArrayList(); try { String content; Object obj; for (int i = 1; i <= columnSize; i++) { content = ""; obj = rs.getObject(i); if (obj != null) { content = rs.getObject(i).toString().trim(); } lstField.add(content); } ((List) map.get(KEY_VALUES)).add(lstField); } catch (Exception e) { logger.error(e); } } }); return map; }
From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public Map query(String sql) { final Map map = new HashMap(); List lstValue = new ArrayList(); map.put(KEY_VALUES, lstValue);/*from www . ja v a2 s .c o m*/ logger.debug(sql); getJdbcTemplate().query(sql, new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { map.put(KEY_META, rs.getMetaData()); int columnSize = rs.getMetaData().getColumnCount(); List lstField = new ArrayList(); try { String content; ; Object obj; for (int i = 1; i <= columnSize; i++) { content = ""; obj = rs.getObject(i); if (obj != null) { content = rs.getObject(i).toString().trim(); } lstField.add(content); } ((List) map.get(KEY_VALUES)).add(lstField); } catch (Exception e) { logger.error(e); } } }); return map; }