List of usage examples for java.sql ResultSet getFloat
float getFloat(String columnLabel) throws SQLException;
ResultSet
object as a float
in the Java programming language. From source file:com.l2jfree.gameserver.datatables.PetDataTable.java
public void loadPetsData() { Connection con = null;/* ww w . jav a 2 s . com*/ try { con = L2DatabaseFactory.getInstance().getConnection(con); PreparedStatement statement = con.prepareStatement( "SELECT typeID, level, expMax, hpMax, mpMax, patk, pdef, matk, mdef, acc, evasion, crit, speed, atk_speed, cast_speed, feedMax, feedbattle, feednormal, loadMax, hpregen, mpregen, owner_exp_taken FROM pets_stats"); ResultSet rset = statement.executeQuery(); int petId, petLevel; while (rset.next()) { petId = rset.getInt("typeID"); petLevel = rset.getInt("level"); //build the petdata for this level L2PetData petData = new L2PetData(); petData.setPetID(petId); petData.setPetLevel(petLevel); petData.setPetMaxExp(rset.getLong("expMax")); petData.setPetMaxHP(rset.getInt("hpMax")); petData.setPetMaxMP(rset.getInt("mpMax")); petData.setPetPAtk(rset.getInt("patk")); petData.setPetPDef(rset.getInt("pdef")); petData.setPetMAtk(rset.getInt("matk")); petData.setPetMDef(rset.getInt("mdef")); petData.setPetAccuracy(rset.getInt("acc")); petData.setPetEvasion(rset.getInt("evasion")); petData.setPetCritical(rset.getInt("crit")); petData.setPetSpeed(rset.getInt("speed")); petData.setPetAtkSpeed(rset.getInt("atk_speed")); petData.setPetCastSpeed(rset.getInt("cast_speed")); petData.setPetMaxFeed(rset.getInt("feedMax")); petData.setPetFeedNormal(rset.getInt("feednormal")); petData.setPetFeedBattle(rset.getInt("feedbattle")); petData.setPetMaxLoad(rset.getInt("loadMax")); petData.setPetRegenHP(rset.getInt("hpregen")); petData.setPetRegenMP(rset.getInt("mpregen")); petData.setOwnerExpTaken(rset.getFloat("owner_exp_taken")); // if its the first data for this petid, we initialize its level FastMap if (!petTable.containsKey(petId)) petTable.put(petId, new FastMap<Integer, L2PetData>()); petTable.get(petId).put(petLevel, petData); } rset.close(); statement.close(); } catch (Exception e) { _log.warn("Could not load pets stats: ", e); } finally { L2DatabaseFactory.close(con); } _log.info("PetDataTable: loaded " + petTable.size() + " pets."); }
From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.data.DBWriter.java
/** Return the cash that the given subject currently has. Checks the subject_cash_holdings * table for the maximum id using a subquery */ public float getCashHoldings(int sessionId, int periodId, int subjectId_db) { Connection conn = null;/*from w ww .ja va 2 s.c o m*/ Object[] results = null; float cash = 0; try { conn = dbc.getConnection(); StringBuffer query = new StringBuffer(); query.append("select max(id) from subject_cash_holdings where "); query.append("subject_id=").append(subjectId_db).append(" and "); query.append("period_id=").append(periodId).append(" and "); query.append("session_id=").append(sessionId); results = dbc.executeQuery(query.toString(), conn); ResultSet rs = (ResultSet) results[0]; rs.next(); int id = rs.getInt(1); dbc.closeQuery(results); query = new StringBuffer(); query.append("select cash_holding from subject_cash_holdings where "); query.append("id=").append(id); results = dbc.executeQuery(query.toString(), conn); rs = (ResultSet) results[0]; rs.next(); cash = rs.getFloat("cash_holding"); } catch (SQLException e) { log.error("Failed to retrieve cash holding of subject " + subjectId_db + ": " + e, e); } finally { dbc.closeQuery(results, conn); } return cash; }
From source file:se.technipelago.weather.chart.Generator.java
private float getValue(Date from, Date to, String column, int func) { PreparedStatement stmt = null; ResultSet result = null; String f;//from w w w . j a v a2 s . c o m float value = 0f; switch (func) { case MIN: f = "MIN"; break; case MAX: f = "MAX"; break; case SUM: f = "SUM"; break; case AVG: f = "AVG"; break; default: throw new IllegalArgumentException("Illegal function: " + func); } init(); try { stmt = conn.prepareStatement("SELECT " + f + "(" + column + ") FROM archive WHERE ts BETWEEN ? AND ?"); stmt.setTimestamp(1, new java.sql.Timestamp(from.getTime())); stmt.setTimestamp(2, new java.sql.Timestamp(to.getTime())); result = stmt.executeQuery(); if (result.next()) { value = result.getFloat(1); } } catch (SQLException ex) { Logger.getLogger(Generator.class.getName()).log(Level.SEVERE, null, ex); } finally { if (result != null) { try { result.close(); } catch (SQLException ex) { log.log(Level.WARNING, "Failed to close ResultSet", ex); } } if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { log.log(Level.WARNING, "Failed to close select statement", ex); } } } return value; }
From source file:csiro.pidsvc.mappingstore.ManagerJson.java
@SuppressWarnings("unchecked") public JSONObject getConditionSets(int page, String searchQuery) throws SQLException { PreparedStatement pst = null; ResultSet rs = null; JSONObject ret = new JSONObject(); final int pageSize = 20; boolean isQueryNotEmpty = searchQuery != null && !searchQuery.isEmpty(); try {/*from w w w .j ava2 s . co m*/ String query = ""; if (isQueryNotEmpty) query += " AND name ILIKE ?"; query = "SELECT COUNT(*) FROM condition_set" + (query.isEmpty() ? "" : " WHERE " + query.substring(5)) + ";\n" + "SELECT * FROM condition_set" + (query.isEmpty() ? "" : " WHERE " + query.substring(5)) + " ORDER BY name LIMIT " + pageSize + " OFFSET " + ((page - 1) * pageSize) + ";"; pst = _connection.prepareStatement(query); for (int i = 1, j = 0; j < 2; ++j) { // Bind parameters twice to two almost identical queries. if (isQueryNotEmpty) pst.setString(i++, "%" + searchQuery.replace("\\", "\\\\") + "%"); } if (pst.execute()) { rs = pst.getResultSet(); rs.next(); ret.put("count", rs.getInt(1)); ret.put("page", page); ret.put("pages", (int) Math.ceil(rs.getFloat(1) / pageSize)); JSONArray jsonArr = new JSONArray(); for (pst.getMoreResults(), rs = pst.getResultSet(); rs.next();) { jsonArr.add(JSONObjectHelper.create("name", rs.getString("name"), "description", rs.getString("description"))); } ret.put("results", jsonArr); } } finally { if (rs != null) rs.close(); if (pst != null) pst.close(); } return ret; }
From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java
public void testDataTypes() throws Exception { Statement stmt = con.createStatement(); ResultSet res = stmt.executeQuery("select * from " + dataTypeTableName + " order by c1"); ResultSetMetaData meta = res.getMetaData(); // row 1/*from w w w. j a v a2s.c om*/ assertTrue(res.next()); // skip the last (partitioning) column since it is always non-null for (int i = 1; i < meta.getColumnCount(); i++) { assertNull(res.getObject(i)); } // row 2 assertTrue(res.next()); assertEquals(-1, res.getInt(1)); assertEquals(false, res.getBoolean(2)); assertEquals(-1.1d, res.getDouble(3)); assertEquals("", res.getString(4)); assertEquals("[]", res.getString(5)); assertEquals("{}", res.getString(6)); assertEquals("{}", res.getString(7)); assertEquals("[null, null, null]", res.getString(8)); assertEquals(-1, res.getByte(9)); assertEquals(-1, res.getShort(10)); assertEquals(-1.0f, res.getFloat(11)); assertEquals(-1, res.getLong(12)); assertEquals("[]", res.getString(13)); assertEquals("{}", res.getString(14)); assertEquals("[null, null]", res.getString(15)); assertEquals("[]", res.getString(16)); assertEquals(null, res.getString(17)); assertEquals(null, res.getTimestamp(17)); assertEquals(null, res.getBigDecimal(18)); assertEquals(null, res.getString(20)); assertEquals(null, res.getDate(20)); // row 3 assertTrue(res.next()); assertEquals(1, res.getInt(1)); assertEquals(true, res.getBoolean(2)); assertEquals(1.1d, res.getDouble(3)); assertEquals("1", res.getString(4)); assertEquals("[1, 2]", res.getString(5)); assertEquals("{1=x, 2=y}", res.getString(6)); assertEquals("{k=v}", res.getString(7)); assertEquals("[a, 9, 2.2]", res.getString(8)); assertEquals(1, res.getByte(9)); assertEquals(1, res.getShort(10)); assertEquals(1.0f, res.getFloat(11)); assertEquals(1, res.getLong(12)); assertEquals("[[a, b], [c, d]]", res.getString(13)); assertEquals("{1={11=12, 13=14}, 2={21=22}}", res.getString(14)); assertEquals("[1, [2, x]]", res.getString(15)); assertEquals("[[{}, 1], [{c=d, a=b}, 2]]", res.getString(16)); assertEquals("2012-04-22 09:00:00.123456789", res.getString(17)); assertEquals("2012-04-22 09:00:00.123456789", res.getTimestamp(17).toString()); assertEquals("123456789.0123456", res.getBigDecimal(18).toString()); assertEquals("2013-01-01", res.getString(20)); assertEquals("2013-01-01", res.getDate(20).toString()); // test getBoolean rules on non-boolean columns assertEquals(true, res.getBoolean(1)); assertEquals(true, res.getBoolean(4)); // no more rows assertFalse(res.next()); }
From source file:org.plasma.sdo.access.provider.jdbc.JDBCDataConverter.java
public Object fromJDBCDataType(ResultSet rs, int columnIndex, int sourceType, PlasmaProperty targetProperty) throws SQLException { Object result = null;//from ww w .ja va 2 s.co m if (targetProperty.getType().isDataType()) { DataType targetDataType = DataType.valueOf(targetProperty.getType().getName()); switch (targetDataType) { case String: case URI: case Month: case MonthDay: case Day: case Time: case Year: case YearMonth: case YearMonthDay: case Duration: result = rs.getString(columnIndex); break; case Date: java.sql.Timestamp ts = rs.getTimestamp(columnIndex); if (ts != null) result = new java.util.Date(ts.getTime()); break; case DateTime: ts = rs.getTimestamp(columnIndex); if (ts != null) result = new java.util.Date(ts.getTime()); break; case Decimal: result = rs.getBigDecimal(columnIndex); break; case Bytes: result = rs.getBytes(columnIndex); break; case Byte: result = rs.getByte(columnIndex); break; case Boolean: result = rs.getBoolean(columnIndex); break; case Character: result = rs.getInt(columnIndex); break; case Double: result = rs.getDouble(columnIndex); break; case Float: result = rs.getFloat(columnIndex); break; case Int: result = rs.getInt(columnIndex); break; case Integer: result = new BigInteger(rs.getString(columnIndex)); break; case Long: result = rs.getLong(columnIndex); break; case Short: result = rs.getShort(columnIndex); break; case Strings: String value = rs.getString(columnIndex); String[] values = value.split("\\s"); List<String> list = new ArrayList<String>(values.length); for (int i = 0; i < values.length; i++) list.add(values[i]); // what no Java 5 sugar for this ?? result = list; break; case Object: default: result = rs.getObject(columnIndex); break; } } else { // FIXME: or get the opposite containing type // of the property and get its pri-key(s) result = rs.getObject(columnIndex); } return result; }
From source file:com.chiorichan.database.DatabaseEngine.java
public static Map<String, Object> convertRow(ResultSet rs) throws SQLException { Map<String, Object> result = Maps.newLinkedHashMap(); ResultSetMetaData rsmd = rs.getMetaData(); int numColumns = rsmd.getColumnCount(); for (int i = 1; i < numColumns + 1; i++) { String columnName = rsmd.getColumnName(i); // Loader.getLogger().info( "Column: " + columnName + " <-> " + rsmd.getColumnTypeName( i ) ); if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) { result.put(columnName, rs.getArray(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.BIT) // Sometimes tinyints are read as bits {//from w w w . ja v a 2 s .c o m result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) { result.put(columnName, rs.getBoolean(columnName)); } else if (rsmd.getColumnTypeName(i).contains("BLOB") || rsmd.getColumnType(i) == java.sql.Types.BINARY) { // BLOG = Max Length 65,535. Recommended that you use a LONGBLOG. byte[] bytes = rs.getBytes(columnName); result.put(columnName, bytes); /* * try * { * result.put( columnName, new String( bytes, "ISO-8859-1" ) ); * } * catch ( UnsupportedEncodingException e ) * { * e.printStackTrace(); * } */ } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) { result.put(columnName, rs.getDouble(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) { result.put(columnName, rs.getFloat(columnName)); } else if (rsmd.getColumnTypeName(i).equals("INT")) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) { result.put(columnName, rs.getNString(columnName)); } else if (rsmd.getColumnTypeName(i).equals("VARCHAR")) { result.put(columnName, rs.getString(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) { result.put(columnName, rs.getDate(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) { result.put(columnName, rs.getTimestamp(columnName)); } else { result.put(columnName, rs.getObject(columnName)); } } return result; }
From source file:com.splicemachine.derby.impl.load.HdfsImportIT.java
@Test public void testImportFromSQL() throws Exception { PreparedStatement ps = methodWatcher.prepareStatement(format("call SYSCS_UTIL.IMPORT_DATA(" + "'%s'," + // schema name "'%s'," + // table name "null," + // insert column list "'%s'," + // file path "','," + // column delimiter "null," + // character delimiter "null," + // timestamp format "'MM/dd/yyyy'," + // date format "'HH.mm.ss'," + // time format "%d," + // max bad records "'%s'," + // bad record dir "null," + // has one line records "null)", // char set spliceSchemaWatcher.schemaName, TABLE_3, getResourceDirectory() + "order_detail_small.csv", 0, BADDIR.getCanonicalPath())); ps.execute();// ww w .j av a 2 s .c om ResultSet rs = methodWatcher .executeQuery(format("select * from %s.%s", spliceSchemaWatcher.schemaName, TABLE_3)); List<String> results = Lists.newArrayList(); while (rs.next()) { String orderId = rs.getString(1); int item_id = rs.getInt(2); int order_amt = rs.getInt(3); Timestamp order_date = rs.getTimestamp(4); int emp_id = rs.getInt(5); int prom_id = rs.getInt(6); int qty_sold = rs.getInt(7); float unit_price = rs.getInt(8); float unit_cost = rs.getFloat(9); float discount = rs.getFloat(10); int cust_id = rs.getInt(11); assertNotNull("No Order Id returned!", orderId); Assert.assertTrue("ItemId incorrect!", item_id > 0); Assert.assertTrue("Order amt incorrect!", order_amt > 0); assertNotNull("order_date incorrect", order_date); Assert.assertTrue("EmpId incorrect", emp_id > 0); Assert.assertEquals("prom_id incorrect", 0, prom_id); Assert.assertTrue("qty_sold incorrect", qty_sold > 0); Assert.assertTrue("unit price incorrect!", unit_price > 0); Assert.assertTrue("unit cost incorrect", unit_cost > 0); Assert.assertEquals("discount incorrect", 0.0f, discount, 1 / 100f); Assert.assertTrue("cust_id incorrect", cust_id != 0); results.add(String.format( "orderId:%s,item_id:%d,order_amt:%d,order_date:%s,emp_id:%d,prom_id:%d," + "qty_sold:%d," + "unit_price:%f,unit_cost:%f,discount:%f,cust_id:%d", orderId, item_id, order_amt, order_date, emp_id, prom_id, qty_sold, unit_price, unit_cost, discount, cust_id)); } Assert.assertTrue("import failed!", results.size() > 0); }
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 {//from w ww .j a v a 2s . com // 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:org.sakaiproject.webservices.SakaiReport.java
protected String toCsvString(ResultSet rs, boolean includeHeaderRow) throws IOException, SQLException { StringWriter stringWriter = new StringWriter(); CsvWriter writer = new CsvWriter(stringWriter, ','); writer.setRecordDelimiter('\n'); writer.setForceQualifier(true);//from w ww . j a v a 2s . c o m ResultSetMetaData rsmd = rs.getMetaData(); int numColumns = rsmd.getColumnCount(); if (includeHeaderRow) { String[] row = new String[numColumns]; for (int i = 1; i < numColumns + 1; i++) { row[i - 1] = rsmd.getColumnLabel(i); } writer.writeRecord(row); } while (rs.next()) { String[] row = new String[numColumns]; for (int i = 1; i < numColumns + 1; i++) { String column_name = rsmd.getColumnName(i); LOG.debug("Column Name=" + column_name + ",type=" + rsmd.getColumnType(i)); switch (rsmd.getColumnType(i)) { case Types.BIGINT: row[i - 1] = String.valueOf(rs.getInt(i)); break; case Types.BOOLEAN: row[i - 1] = String.valueOf(rs.getBoolean(i)); break; case Types.BLOB: row[i - 1] = rs.getBlob(i).toString(); break; case Types.DOUBLE: row[i - 1] = String.valueOf(rs.getDouble(i)); break; case Types.FLOAT: row[i - 1] = String.valueOf(rs.getFloat(i)); break; case Types.INTEGER: row[i - 1] = String.valueOf(rs.getInt(i)); break; case Types.LONGVARCHAR: row[i - 1] = rs.getString(i); break; case Types.NVARCHAR: row[i - 1] = rs.getNString(i); break; case Types.VARCHAR: row[i - 1] = rs.getString(i); break; case Types.TINYINT: row[i - 1] = String.valueOf(rs.getInt(i)); break; case Types.SMALLINT: row[i - 1] = String.valueOf(rs.getInt(i)); break; case Types.DATE: row[i - 1] = rs.getDate(i).toString(); break; case Types.TIMESTAMP: row[i - 1] = rs.getTimestamp(i).toString(); break; default: row[i - 1] = rs.getString(i); break; } LOG.debug("value: " + row[i - 1]); } writer.writeRecord(row); //writer.endRecord(); } LOG.debug("csv output:" + stringWriter.toString()); return stringWriter.toString(); }