List of usage examples for java.sql ResultSet getBigDecimal
BigDecimal getBigDecimal(String columnLabel) throws SQLException;
ResultSet
object as a java.math.BigDecimal
with full precision. From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccOracle.CFAccOracleAccountTable.java
protected CFAccAccountBuff unpackAccountResultSetToBuff(ResultSet resultSet) throws SQLException { final String S_ProcName = "unpackAccountResultSetToBuff"; int idxcol = 1; CFAccAccountBuff buff = schema.getFactoryAccount().newBuff(); {/*from www. j a v a2 s. com*/ String colString = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setCreatedByUserId(null); } else if ((colString == null) || (colString.length() <= 0)) { buff.setCreatedByUserId(null); } else { buff.setCreatedByUserId(UUID.fromString(colString)); } idxcol++; colString = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setCreatedAt(null); } else if ((colString == null) || (colString.length() <= 0)) { buff.setCreatedAt(null); } else { buff.setCreatedAt(CFAccOracleSchema.convertTimestampString(colString)); } idxcol++; colString = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setUpdatedByUserId(null); } else if ((colString == null) || (colString.length() <= 0)) { buff.setUpdatedByUserId(null); } else { buff.setUpdatedByUserId(UUID.fromString(colString)); } idxcol++; colString = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setUpdatedAt(null); } else if ((colString == null) || (colString.length() <= 0)) { buff.setUpdatedAt(null); } else { buff.setUpdatedAt(CFAccOracleSchema.convertTimestampString(colString)); } idxcol++; } buff.setRequiredTenantId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredAccountCode(resultSet.getString(idxcol)); idxcol++; buff.setRequiredDescription(resultSet.getString(idxcol)); idxcol++; buff.setRequiredCurrencyId(resultSet.getShort(idxcol)); idxcol++; buff.setRequiredBalance(resultSet.getBigDecimal(idxcol)); idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalRollupTenantId(null); } else { buff.setOptionalRollupTenantId(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalRollupAccountId(null); } else { buff.setOptionalRollupAccountId(colVal); } } idxcol++; buff.setRequiredRevision(resultSet.getInt(idxcol)); return (buff); }
From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java
private List<LogMessageData> toLogMessageDataInternal(ResultSet rs, List<LogMessageData> logMessageData) { try {/*from ww w . j a v a2s . com*/ // 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:com.app.das.business.dao.SearchDAO.java
/** * ?? ? ./* w ww. j a v a 2 s. c o m*/ * @param searchConditionDO ? ? DataObject * @param commonDO * @return PageDO ?? ?? ? PageDO * @throws Exception */ public PageDO selectRequestDownList(SearchConditionDO searchConditionDO, DASCommonDO commonDO) throws Exception { PageDO pageDO = new PageDO(); StringBuffer buf = new StringBuffer(); buf.append( "\n select * FROM \n"); buf.append( "\n ( \n"); buf.append(SearchStatement.selectRequestDownListQuery(commonDO, DASBusinessConstants.PageQueryFlag.NORMAL)); buf.append( "\n ) AS temp \n"); buf.append("\n where temp.rownum >= ? and temp.rownum <=? \n"); buf.append("\n WITH UR "); //Page? ? . int page = searchConditionDO.getPage(); if (page == 0) { page = 1; } Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; try { con = DBService.getInstance().getConnection(); //logger.debug("######selectRequestDownList######## con : " + con); //? . int totalCount = getTotalCount(con, SearchStatement.selectRequestDownListQuery(commonDO, DASBusinessConstants.PageQueryFlag.TOTAL_COUNT)); stmt = con.prepareStatement(buf.toString()); int rowPerPage = searchConditionDO.getRowPerPage(); if (rowPerPage == 0) { rowPerPage = DASBusinessConstants.PageRowCount.DOWN_REQ_ROW_COUNT; } //? ?? row ?? row . int endNum = page * rowPerPage; int startNum = endNum - (rowPerPage - 1); int index = 0; stmt.setInt(++index, startNum); stmt.setInt(++index, endNum); rs = stmt.executeQuery(); int indexCount = 0; List resultList = new ArrayList(); while (rs.next()) { ReqDownItemDO item = new ReqDownItemDO(); item.setSerialNo(rs.getInt("rownum")); item.setCartNo(rs.getBigDecimal("CART_NO")); item.setCartSeq(rs.getInt("CART_SEQ")); item.setVdQltyNm(rs.getString("VD_QLTY_NM")); item.setAspRtoNm(rs.getString("ASP_RTO_NM")); item.setPgmNm(rs.getString("PGM_NM")); item.setEpisNo(rs.getInt("EPIS_NO")); item.setSom(rs.getString("SOM")); item.setEom(rs.getString("EOM")); item.setRistClfNm(rs.getString("RIST_CLF_NM")); resultList.add(item); } int totalPageCount = totalCount / rowPerPage + (totalCount % rowPerPage != 0 ? 1 : 0); //? List . pageDO.setPageItems(resultList); //? ? Page . pageDO.setTotalPageCount(totalPageCount); return pageDO; } catch (Exception e) { logger.error(buf.toString()); throw e; } finally { release(rs, stmt, con); } }
From source file:edu.ku.brc.specify.Specify.java
/** * /*from w w w . j a v a 2s. c om*/ */ protected void localities() { Connection connection = DBConnection.getInstance().getConnection(); Statement stmt = null; Statement stmt2 = null; try { stmt = connection.createStatement(); stmt2 = connection.createStatement(); String sql = "SELECT l.LocalityID, l.LocalityName, g.FullName, l.Latitude1, l.Longitude1 FROM locality l INNER JOIN geography g ON l.GeographyID = g.GeographyID"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String currLocalityName = rs.getString(2); ResultSet rs1 = stmt2.executeQuery(sql + " WHERE g.FullName = \"" + rs.getString(3) + "\" AND l.LocalityID <> " + rs.getInt(1)); while (rs1.next()) { String localityName = rs1.getString(2); int distance = StringUtils.getLevenshteinDistance(currLocalityName, localityName); //log.error(rs.getInt(1) + " "+ rs1.getInt(1) + " "+ distance); if (distance < 6) { log.error("----- " + distance + "\n" + currLocalityName + "\n" + localityName); log.error(rs.getBigDecimal(4) + "," + rs.getBigDecimal(5) + "\n" + rs1.getBigDecimal(4) + "," + rs1.getBigDecimal(5)); } } rs1.close(); } rs.close(); } catch (SQLException ex) { ex.printStackTrace(); } finally { try { if (stmt != null) { stmt.close(); } if (stmt2 != null) { stmt2.close(); } } catch (SQLException ex) { ex.printStackTrace(); } } }
From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java
public List<String> toStringList(ResultSet rs) throws Exception { List<String> list = new ArrayList<String>(); try {/* w ww . ja v a 2 s . co m*/ // we will need the column names, this will save the table meta-data like column nmae. java.sql.ResultSetMetaData rsmd = rs.getMetaData(); //loop through the ResultSet while (rs.next()) { //figure out how many columns there are int numColumns = rsmd.getColumnCount(); //each row in the ResultSet will be converted to a JSON Object StringBuilder builder = new StringBuilder(); // loop through all the columns and place them into the JSON Object for (int i = 1; i < numColumns + 1; i++) { String column_name = rsmd.getColumnName(i); if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) { builder.append(rs.getArray(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) { builder.append(rs.getInt(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) { builder.append(rs.getBoolean(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) { builder.append(rs.getBlob(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) { builder.append(rs.getDouble(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) { builder.append(rs.getFloat(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) { builder.append(rs.getInt(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) { builder.append(rs.getNString(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) { // temp = rs.getString(column_name); //saving column data to temp variable // temp = ESAPI.encoder().canonicalize(temp); //decoding data to base state // temp = ESAPI.encoder().encodeForHTML(temp); //encoding to be browser safe // obj.put(column_name, temp); //putting data into JSON object // builder.append(rs.getNString(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) { builder.append(rs.getInt(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) { builder.append(rs.getInt(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) { builder.append(rs.getDate(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) { builder.append(rs.getTime(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) { builder.append(rs.getTimestamp(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) { builder.append(rs.getBigDecimal(column_name)); } else { builder.append(rs.getObject(column_name)); } } //end foreach list.add(builder.toString()); } //end while } catch (Exception e) { e.printStackTrace(); } return list; //return String list }
From source file:Logica.Usuario.java
/** * * @param mes/*from w w w . j av a 2s . co m*/ * @return * @throws RemoteException * * Genera el informe de descargos de acuerdo al mes ingresado */ @Override public ArrayList<informeDescargos> generarInforme(String mes) throws RemoteException { EntityManagerFactory emf = Persistence.createEntityManagerFactory("Biot_ServerPU"); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; String statement = "create view gInforme1 as(select i.CINTERNO, i.INVENTARIO, i.DESCRIPCION, i.CANTIDAD as enInventario, d.FECHA as fecha, (select nombre from usuario where id = d.id_usuario) as nombre ,d.id_usuario as id, d.AREA\n" + "from item i right outer join DESCARGO d\n" + "on i.CINTERNO = d.CINTERNO);"; String statement2 = "create view gInforme2 as( select cinterno, inventario, descripcion, eninventario, fecha, nombre, id, area from gInforme1 where gInforme1.fecha like ?);"; String statement3 = "create view gInforme3 as(select d.CINTERNO, \"\",sum(d.cantidad) as suma from descargo d, descargo dd where dd.id= d.id group by d.CINTERNO);"; String statement4 = "select distinct p2.cinterno, p2.inventario, p2.descripcion, p2.eninventario, p3.suma, p2.nombre, p2.id, p2.area\n" + " from gInforme2 p2 , gInforme3 p3 where p2.cinterno = p3.CINTERNO; "; informeDescargos fila = null; ArrayList<informeDescargos> listado = new ArrayList<>(); System.out.println(statement); System.out.println(statement2); System.out.println(statement3); System.out.println(statement4); try { con = Conexion.conexion.getConnection(); mes = "%-" + mes + "-%"; ps = con.prepareStatement(statement); ps.executeUpdate(); ps = con.prepareStatement(statement2); ps.setString(1, mes); ps.executeUpdate(); ps = con.prepareStatement(statement3); ps.executeUpdate(); ps = con.prepareStatement(statement4); rs = ps.executeQuery(); while (rs.next()) { fila = new informeDescargos(rs.getString(1), rs.getString(2), rs.getString(3), rs.getFloat(4), rs.getFloat(5), rs.getString(6), rs.getBigDecimal(7), rs.getString(8)); listado.add(fila); } ps.executeUpdate("drop view gInforme1;"); ps.executeUpdate("drop view gInforme2;"); ps.executeUpdate("drop view gInforme3;"); } catch (SQLException ex) { Logger.getLogger(Usuario.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ps != null) { ps.close(); } if (rs != null) { rs.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.out.println("Error cerrando conexion"); } } return listado; }
From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java
private Map<String, Object> getMetaDataMap(String channelId, long messageId, int metaDataId) { PreparedStatement statement = null; ResultSet resultSet = null; try {/*w w w . ja va 2 s. c o m*/ Map<String, Object> values = new HashMap<String, Object>(); values.put("localChannelId", getLocalChannelId(channelId)); // do not cache this statement since metadata columns may be added/removed statement = connection.prepareStatement(querySource.getQuery("getMetaDataMap", values)); statement.setLong(1, messageId); statement.setInt(2, metaDataId); Map<String, Object> metaDataMap = new HashMap<String, Object>(); resultSet = statement.executeQuery(); if (resultSet.next()) { ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); int columnCount = resultSetMetaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { MetaDataColumnType metaDataColumnType = MetaDataColumnType .fromSqlType(resultSetMetaData.getColumnType(i)); Object value = null; switch (metaDataColumnType) {//@formatter:off case STRING: value = resultSet.getString(i); break; case NUMBER: value = resultSet.getBigDecimal(i); break; case BOOLEAN: value = resultSet.getBoolean(i); break; case TIMESTAMP: Timestamp timestamp = resultSet.getTimestamp(i); if (timestamp != null) { value = Calendar.getInstance(); ((Calendar) value).setTimeInMillis(timestamp.getTime()); } break; default: throw new Exception("Unrecognized MetaDataColumnType"); } //@formatter:on metaDataMap.put(resultSetMetaData.getColumnName(i).toUpperCase(), value); } } return metaDataMap; } catch (Exception e) { throw new DonkeyDaoException(e); } finally { close(resultSet); close(statement); } }
From source file:org.apache.phoenix.end2end.index.IndexExpressionIT.java
public void helpTestAddPKColumnToTable(boolean mutable, boolean local) throws Exception { ResultSet rs; PreparedStatement stmt;/*www. ja v a 2 s . co m*/ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { conn.setAutoCommit(false); // make sure that the tables are empty, but reachable conn.createStatement() .execute("CREATE TABLE t" + " (k VARCHAR NOT NULL PRIMARY KEY, v1 VARCHAR, v2 VARCHAR)"); String dataTableQuery = "SELECT * FROM t"; rs = conn.createStatement().executeQuery(dataTableQuery); assertFalse(rs.next()); String indexName = "IT_" + (mutable ? "M" : "IM") + "_" + (local ? "L" : "H"); conn.createStatement().execute( "CREATE " + (local ? "LOCAL" : "") + " INDEX " + indexName + " ON t (v1 || '_' || v2)"); String indexTableQuery = "SELECT * FROM " + indexName; rs = conn.createStatement().executeQuery(indexTableQuery); assertFalse(rs.next()); // load some data into the table stmt = conn.prepareStatement("UPSERT INTO t VALUES(?,?,?)"); stmt.setString(1, "a"); stmt.setString(2, "x"); stmt.setString(3, "1"); stmt.execute(); conn.commit(); assertIndexExists(conn, true); conn.createStatement().execute("ALTER TABLE t ADD v3 VARCHAR, k2 DECIMAL PRIMARY KEY"); rs = conn.getMetaData().getPrimaryKeys("", "", "T"); assertTrue(rs.next()); assertEquals("K", rs.getString("COLUMN_NAME")); assertEquals(1, rs.getShort("KEY_SEQ")); assertTrue(rs.next()); assertEquals("K2", rs.getString("COLUMN_NAME")); assertEquals(2, rs.getShort("KEY_SEQ")); rs = conn.getMetaData().getPrimaryKeys("", "", indexName); assertTrue(rs.next()); assertEquals(IndexUtil.INDEX_COLUMN_NAME_SEP + "(V1 || '_' || V2)", rs.getString("COLUMN_NAME")); int offset = local ? 1 : 0; assertEquals(offset + 1, rs.getShort("KEY_SEQ")); assertTrue(rs.next()); assertEquals(IndexUtil.INDEX_COLUMN_NAME_SEP + "K", rs.getString("COLUMN_NAME")); assertEquals(offset + 2, rs.getShort("KEY_SEQ")); assertTrue(rs.next()); assertEquals(IndexUtil.INDEX_COLUMN_NAME_SEP + "K2", rs.getString("COLUMN_NAME")); assertEquals(offset + 3, rs.getShort("KEY_SEQ")); // verify data table rows rs = conn.createStatement().executeQuery(dataTableQuery); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals("x", rs.getString(2)); assertEquals("1", rs.getString(3)); assertNull(rs.getBigDecimal(4)); assertFalse(rs.next()); // verify index table rows rs = conn.createStatement().executeQuery(indexTableQuery); assertTrue(rs.next()); assertEquals("x_1", rs.getString(1)); assertEquals("a", rs.getString(2)); assertNull(rs.getBigDecimal(3)); assertFalse(rs.next()); // load some data into the table stmt = conn.prepareStatement("UPSERT INTO t(K,K2,V1,V2) VALUES(?,?,?,?)"); stmt.setString(1, "b"); stmt.setBigDecimal(2, BigDecimal.valueOf(2)); stmt.setString(3, "y"); stmt.setString(4, "2"); stmt.execute(); conn.commit(); // verify data table rows rs = conn.createStatement().executeQuery(dataTableQuery); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals("x", rs.getString(2)); assertEquals("1", rs.getString(3)); assertNull(rs.getString(4)); assertNull(rs.getBigDecimal(5)); assertTrue(rs.next()); assertEquals("b", rs.getString(1)); assertEquals("y", rs.getString(2)); assertEquals("2", rs.getString(3)); assertNull(rs.getString(4)); assertEquals(BigDecimal.valueOf(2), rs.getBigDecimal(5)); assertFalse(rs.next()); // verify index table rows rs = conn.createStatement().executeQuery(indexTableQuery); assertTrue(rs.next()); assertEquals("x_1", rs.getString(1)); assertEquals("a", rs.getString(2)); assertNull(rs.getBigDecimal(3)); assertTrue(rs.next()); assertEquals("y_2", rs.getString(1)); assertEquals("b", rs.getString(2)); assertEquals(BigDecimal.valueOf(2), rs.getBigDecimal(3)); assertFalse(rs.next()); } finally { conn.close(); } }
From source file:com.nway.spring.jdbc.bean.JavassistBeanProcessor.java
private Object processColumn(ResultSet rs, int index, Class<?> propType, String writer, StringBuilder handler) throws SQLException { if (propType.equals(String.class)) { handler.append("bean.").append(writer).append("(").append("$1.getString(").append(index).append("));"); return rs.getString(index); } else if (propType.equals(Integer.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getInt(").append(index).append("));"); return rs.getInt(index); } else if (propType.equals(Integer.class)) { handler.append("bean.").append(writer).append("(").append("integerValue($1.getInt(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Integer.class); } else if (propType.equals(Long.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getLong(").append(index).append("));"); return rs.getLong(index); } else if (propType.equals(Long.class)) { handler.append("bean.").append(writer).append("(").append("longValue($1.getLong(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Long.class); } else if (propType.equals(java.sql.Date.class)) { handler.append("bean.").append(writer).append("(").append("$1.getDate(").append(index).append("));"); return rs.getDate(index); } else if (propType.equals(java.util.Date.class) || propType.equals(Timestamp.class)) { handler.append("bean.").append(writer).append("(").append("$1.getTimestamp(").append(index) .append("));"); return rs.getTimestamp(index); } else if (propType.equals(Double.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getDouble(").append(index).append("));"); return rs.getDouble(index); } else if (propType.equals(Double.class)) { handler.append("bean.").append(writer).append("(").append("doubleValue($1.getDouble(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Double.class); } else if (propType.equals(Float.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getFloat(").append(index).append("));"); return rs.getFloat(index); } else if (propType.equals(Float.class)) { handler.append("bean.").append(writer).append("(").append("floatValue($1.getFloat(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Float.class); } else if (propType.equals(Time.class)) { handler.append("bean.").append(writer).append("(").append("$1.getTime(").append(index).append("));"); return rs.getTime(index); } else if (propType.equals(Boolean.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getBoolean(").append(index).append("));"); return rs.getBoolean(index); } else if (propType.equals(Boolean.class)) { handler.append("bean.").append(writer).append("(").append("booleanValue($1.getBoolean(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Boolean.class); } else if (propType.equals(byte[].class)) { handler.append("bean.").append(writer).append("(").append("$1.getBytes(").append(index).append("));"); return rs.getBytes(index); } else if (BigDecimal.class.equals(propType)) { handler.append("bean.").append(writer).append("(").append("$1.getBigDecimal(").append(index) .append("));"); return rs.getBigDecimal(index); } else if (Blob.class.equals(propType)) { handler.append("bean.").append(writer).append("(").append("$1.getBlob(").append(index).append("));"); return rs.getBlob(index); } else if (Clob.class.equals(propType)) { handler.append("bean.").append(writer).append("(").append("$1.getClob(").append(index).append("));"); return rs.getClob(index); } else if (propType.equals(Short.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getShort(").append(index).append("));"); return rs.getShort(index); } else if (propType.equals(Short.class)) { handler.append("bean.").append(writer).append("(").append("shortValue($1.getShort(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Short.class); } else if (propType.equals(Byte.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getByte(").append(index).append("));"); return rs.getByte(index); } else if (propType.equals(Byte.class)) { handler.append("bean.").append(writer).append("(").append("byteValue($1.getByte(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Byte.class); } else {//w w w. j a v a 2 s.com handler.append("bean.").append(writer).append("(").append("(").append(propType.getName()).append(")") .append("$1.getObject(").append(index).append("));"); return rs.getObject(index); } }
From source file:helma.objectmodel.db.NodeManager.java
/** * Create a new Node from a ResultSet./*from w w w .ja v a 2s .com*/ */ public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset) throws SQLException, IOException, ClassNotFoundException { HashMap propBuffer = new HashMap(); String id = null; String name = null; String protoName = dbm.getTypeName(); DbMapping dbmap = dbm; Node node = new Node(safe); for (int i = 0; i < columns.length; i++) { int columnNumber = i + 1 + offset; // set prototype? if (columns[i].isPrototypeField()) { String protoId = rs.getString(columnNumber); protoName = dbm.getPrototypeName(protoId); if (protoName != null) { dbmap = getDbMapping(protoName); if (dbmap == null) { // invalid prototype name! app.logError("No prototype defined for prototype mapping \"" + protoName + "\" - Using default prototype \"" + dbm.getTypeName() + "\"."); dbmap = dbm; protoName = dbmap.getTypeName(); } } } // set id? if (columns[i].isIdField()) { id = rs.getString(columnNumber); // if id == null, the object doesn't actually exist - return null if (id == null) { return null; } } // set name? if (columns[i].isNameField()) { name = rs.getString(columnNumber); } Property newprop = new Property(node); switch (columns[i].getType()) { case Types.BIT: case Types.BOOLEAN: newprop.setBooleanValue(rs.getBoolean(columnNumber)); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: newprop.setIntegerValue(rs.getLong(columnNumber)); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: newprop.setFloatValue(rs.getDouble(columnNumber)); break; case Types.DECIMAL: case Types.NUMERIC: BigDecimal num = rs.getBigDecimal(columnNumber); if (num == null) { break; } if (num.scale() > 0) { newprop.setFloatValue(num.doubleValue()); } else { newprop.setIntegerValue(num.longValue()); } break; case Types.VARBINARY: case Types.BINARY: newprop.setJavaObjectValue(rs.getBytes(columnNumber)); break; case Types.BLOB: case Types.LONGVARBINARY: { InputStream in = rs.getBinaryStream(columnNumber); if (in == null) { break; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int read; while ((read = in.read(buffer)) > -1) { bout.write(buffer, 0, read); } newprop.setJavaObjectValue(bout.toByteArray()); } break; case Types.LONGVARCHAR: try { newprop.setStringValue(rs.getString(columnNumber)); } catch (SQLException x) { Reader in = rs.getCharacterStream(columnNumber); if (in == null) { newprop.setStringValue(null); break; } StringBuffer out = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = in.read(buffer)) > -1) { out.append(buffer, 0, read); } newprop.setStringValue(out.toString()); } break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: newprop.setStringValue(rs.getString(columnNumber)); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: newprop.setDateValue(rs.getTimestamp(columnNumber)); break; case Types.NULL: newprop.setStringValue(null); break; case Types.CLOB: Clob cl = rs.getClob(columnNumber); if (cl == null) { newprop.setStringValue(null); break; } char[] c = new char[(int) cl.length()]; Reader isr = cl.getCharacterStream(); isr.read(c); newprop.setStringValue(String.copyValueOf(c)); break; default: newprop.setStringValue(rs.getString(columnNumber)); break; } if (rs.wasNull()) { newprop.setStringValue(null); } propBuffer.put(columns[i].getName(), newprop); // mark property as clean, since it's fresh from the db newprop.dirty = false; } if (id == null) { return null; } else { Transactor tx = Transactor.getInstance(); if (tx != null) { // Check if the node is already registered with the transactor - // it may be in the process of being DELETED, but do return the // new node if the old one has been marked as INVALID. DbKey key = new DbKey(dbmap, id); Node dirtyNode = tx.getDirtyNode(key); if (dirtyNode != null && dirtyNode.getState() != Node.INVALID) { return dirtyNode; } } } Hashtable propMap = new Hashtable(); DbColumn[] columns2 = dbmap.getColumns(); for (int i = 0; i < columns2.length; i++) { Relation rel = columns2[i].getRelation(); if (rel != null && rel.isPrimitiveOrReference()) { Property prop = (Property) propBuffer.get(columns2[i].getName()); if (prop == null) { continue; } prop.setName(rel.propName); // if the property is a pointer to another node, change the property type to NODE if (rel.isReference() && rel.usesPrimaryKey()) { // FIXME: References to anything other than the primary key are not supported prop.convertToNodeReference(rel); } propMap.put(rel.propName, prop); } } node.init(dbmap, id, name, protoName, propMap); return node; }