Example usage for java.sql ResultSet getFloat

List of usage examples for java.sql ResultSet getFloat

Introduction

In this page you can find the example usage for java.sql ResultSet getFloat.

Prototype

float getFloat(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a float in the Java programming language.

Usage

From source file:org.etudes.component.app.jforum.JForumServiceImpl.java

/**
 * Gets the user evaluation//from  ww w .j av a 2s  .  c o m
 * 
 * @param grade      The grade
 * 
 * @param userId   The user id
 * 
 * @return      Evaluation or null if there is no evaluation
 */
protected Evaluation getUserEvaluation(Grade grade, String userId) {
    if (grade == null)
        throw new IllegalArgumentException();
    if (userId == null)
        throw new IllegalArgumentException();

    // user evaluation
    Evaluation evaluation = null;

    StringBuilder sql;
    Object[] fields;
    int i;

    sql = new StringBuilder();
    sql.append(
            "SELECT evaluation_id, grade_id, user_id, sakai_user_id, score, comments, evaluated_by, evaluated_date, released ");
    sql.append(" FROM jforum_evaluations");
    sql.append(" WHERE grade_id = ? AND sakai_user_id = ?");

    fields = new Object[2];
    i = 0;
    fields[i++] = grade.getId();
    fields[i++] = userId;

    final List<Evaluation> evaluations = new ArrayList<Evaluation>();

    this.sqlService.dbRead(sql.toString(), fields, new SqlReader() {
        public Object readSqlResultRecord(ResultSet result) {
            try {
                Evaluation evaluation = new EvaluationImpl();
                ((EvaluationImpl) evaluation).setId(result.getInt("evaluation_id"));
                ((EvaluationImpl) evaluation).setGradeId(result.getInt("grade_id"));
                ((EvaluationImpl) evaluation).setSakaiUserId(result.getString("sakai_user_id"));
                evaluation.setScore(result.getFloat("score"));
                ((EvaluationImpl) evaluation).setEvaluatedBy(result.getInt("evaluated_by"));

                if (result.getDate("evaluated_date") != null) {
                    Timestamp dueDate = result.getTimestamp("evaluated_date");
                    ((EvaluationImpl) evaluation).setEvaluatedDate(dueDate);
                } else {
                    ((EvaluationImpl) evaluation).setEvaluatedDate(null);
                }

                evaluation.setReleased(result.getInt("released") == 1);

                evaluations.add(evaluation);

                return null;
            } catch (SQLException e) {
                if (logger.isWarnEnabled()) {
                    logger.warn("getUserEvaluation: " + e, e);
                }
                return null;
            }
        }
    });

    if (evaluations.size() == 1) {
        evaluation = evaluations.get(0);
    }

    return evaluation;
}

From source file:org.springframework.jdbc.core.AbstractBeanPropertyRowMapper.java

protected Object doMapRow(ResultSet rs, int rowNumber) throws SQLException {
    if (getMappedClass() == null)
        throw new InvalidDataAccessApiUsageException("Target class was not specified - it is mandatory");
    Object result;/*from w  ww .  j a va2 s .  c o  m*/
    try {
        result = this.defaultConstruct.newInstance((Object[]) null);
    } catch (IllegalAccessException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InvocationTargetException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InstantiationException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    }
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    for (int i = 1; i <= columns; i++) {
        String column = JdbcUtils.lookupColumnName(rsmd, i).toLowerCase();
        PersistentField fieldMeta = (PersistentField) this.mappedFields.get(column);
        if (fieldMeta != null) {
            BeanWrapper bw = new BeanWrapperImpl(mappedClass);
            bw.setWrappedInstance(result);
            fieldMeta.setSqlType(rsmd.getColumnType(i));
            Object value = null;
            Class fieldType = fieldMeta.getJavaType();
            if (fieldType.equals(String.class)) {
                value = rs.getString(column);
            } else if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) {
                value = new Byte(rs.getByte(column));
            } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) {
                value = new Short(rs.getShort(column));
            } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
                value = new Integer(rs.getInt(column));
            } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
                value = new Long(rs.getLong(column));
            } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
                value = new Float(rs.getFloat(column));
            } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
                value = new Double(rs.getDouble(column));
            } else if (fieldType.equals(BigDecimal.class)) {
                value = rs.getBigDecimal(column);
            } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
                value = (rs.getBoolean(column)) ? Boolean.TRUE : Boolean.FALSE;
            } else if (fieldType.equals(java.util.Date.class) || fieldType.equals(java.sql.Timestamp.class)
                    || fieldType.equals(java.sql.Time.class) || fieldType.equals(Number.class)) {
                value = JdbcUtils.getResultSetValue(rs, rs.findColumn(column));
            }
            if (value != null) {
                if (bw.isWritableProperty(fieldMeta.getFieldName())) {
                    try {
                        if (logger.isDebugEnabled() && rowNumber == 0) {
                            logger.debug("Mapping column named \"" + column + "\""
                                    + " containing values of SQL type " + fieldMeta.getSqlType()
                                    + " to property \"" + fieldMeta.getFieldName() + "\"" + " of type "
                                    + fieldMeta.getJavaType());
                        }
                        bw.setPropertyValue(fieldMeta.getFieldName(), value);
                    } catch (NotWritablePropertyException ex) {
                        throw new DataRetrievalFailureException(
                                "Unable to map column " + column + " to property " + fieldMeta.getFieldName(),
                                ex);
                    }
                } else {
                    if (rowNumber == 0) {
                        logger.warn("Unable to access the setter for " + fieldMeta.getFieldName()
                                + ".  Check that " + "set" + StringUtils.capitalize(fieldMeta.getFieldName())
                                + " is declared and has public access.");
                    }
                }
            }
        }
    }
    return result;
}

From source file:se.technipelago.weather.chart.Generator.java

private CategoryDataset createRainDataset(final Date begin, final Date end) throws SQLException {
    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    PreparedStatement stmt = null;
    ResultSet result = null;

    Calendar cal = Calendar.getInstance();
    cal.setTime(begin);//from w ww .j  a v  a  2 s  .c o m
    int y1 = cal.get(Calendar.YEAR);
    int m1 = cal.get(Calendar.MONTH);
    cal.setTime(end);
    int y2 = cal.get(Calendar.YEAR);
    int m2 = cal.get(Calendar.MONTH);
    long spanDays = (end.getTime() - begin.getTime()) / 1000 / 60 / 60 / 24;
    DateFormat fmt = spanDays < 40 ? DAY : M;
    try {
        final java.sql.Timestamp sqlBegin = new java.sql.Timestamp(begin.getTime());
        final java.sql.Timestamp sqlEnd = new java.sql.Timestamp(end.getTime());
        if (spanDays < 100) {
            stmt = conn.prepareStatement(
                    "SELECT date_format(ts, '%Y-%m-%d') AS day, SUM(rain) AS rain FROM archive WHERE ts BETWEEN ? AND ? GROUP BY 1");
        } else {
            stmt = conn.prepareStatement(
                    "SELECT date_format(ts, '%Y-%m-15') AS day, SUM(rain) AS rain FROM archive WHERE ts BETWEEN ? AND ? GROUP BY 1");
        }

        stmt.setTimestamp(1, sqlBegin);
        stmt.setTimestamp(2, sqlEnd);
        result = stmt.executeQuery();

        while (result.next()) {
            final String ymd = result.getString(1);
            final Date day = YMD.parse(ymd);
            final float rain = result.getFloat(2);
            dataset.addValue(rain, "Rain", fmt.format(day));
        }
    } catch (ParseException e) {
        log.log(Level.SEVERE, "Failed to parse rain date", e);
    } finally {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                log.log(Level.SEVERE, "Failed to close ResultSet", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                log.log(Level.WARNING, "Failed to close select statement", ex);
            }
        }
    }

    return dataset;
}

From source file:com.emc.plants.service.impl.ReportGeneratorBean.java

/** 
 * Run the report to get the top zip codes for a range of dates.
 *
 * @param startdate Start of date range.
 * @param enddate End of date range.//from   w ww .j  a v  a2s.  co  m
 * @param quantity Number of items to return in report.
 * @param reportFormat - Report format information.
 * @return Report containing results.
 */
@SuppressWarnings("unchecked")
public Report getTopSellingZipsForDates(java.util.Date startdate, java.util.Date enddate, int quantity,
        ReportFormat reportFormat) {
    Report report = null;
    Connection conn = null;
    ResultSet results = null;
    PreparedStatement sqlStatement = null;
    try {
        // Establish connection to datasource.
        String orderInfoTableName = "ORDER1";

        DataSource ds = (DataSource) Util.getInitialContext().lookup("jdbc/PlantsByWebSphereDataSource");
        conn = ds.getConnection();

        // Set sort order of ascending or descending.
        String sortOrder;
        if (reportFormat.isAscending())
            sortOrder = "ASC";
        else
            sortOrder = "DESC";

        // Set up where by clause.
        String startDateString = Long.toString(startdate.getTime());
        if (startDateString.length() < 14) {
            StringBuffer sb = new StringBuffer(Util.ZERO_14);
            sb.replace((14 - startDateString.length()), 14, startDateString);
            startDateString = sb.toString();
        }
        String endDateString = Long.toString(enddate.getTime());
        if (endDateString.length() < 14) {
            StringBuffer sb = new StringBuffer(Util.ZERO_14);
            sb.replace((14 - endDateString.length()), 14, endDateString);
            endDateString = sb.toString();
        }
        String whereString = " WHERE sellDate BETWEEN '" + startDateString + "' AND '" + endDateString + "' ";

        // Create SQL statement.
        String sqlString = "SELECT billZip, SUM(profit) AS PROFITS FROM " + orderInfoTableName + whereString
                + " GROUP BY billZip ORDER BY PROFITS " + sortOrder + ", billZip";

        Util.debug("sqlstring=" + sqlString + "=");
        sqlStatement = conn.prepareStatement(sqlString);
        results = sqlStatement.executeQuery();
        int i;

        // Initialize vectors to store data in.
        Vector[] vecs = new Vector[2];
        for (i = 0; i < vecs.length; i++) {
            vecs[i] = new Vector();
        }

        // Sift thru results.
        int count = 0;
        while ((results.next()) && (count < quantity)) {
            count++;
            i = 1;
            vecs[0].addElement(results.getString(i++));
            vecs[1].addElement(new Float(results.getFloat(i++)));
        }

        // Create report.
        report = new Report();
        report.setReportFieldByRow(Report.ORDER_BILLZIP, vecs[0]);
        report.setReportFieldByRow(Report.PROFITS, vecs[1]);
    } catch (NamingException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally { // Clean up.
        try {
            if (results != null)
                results.close();
        } catch (Exception ignore) {
        }

        try {
            if (sqlStatement != null)
                sqlStatement.close();
        } catch (Exception ignore) {
        }

        // Close Connection.
        try {
            if (conn != null)
                conn.close();
        } catch (Exception ignore) {
        }
    }

    return report;
}

From source file:org.etudes.component.app.jforum.JForumServiceImpl.java

/**
 * Gets the user site evaluations// www. jav  a  2 s .c  o  m
 * 
 * @param context   The context/site id
 * 
 * @param userId   The jforum user id
 * 
 * @return   List of user site evaluations
 */
protected List<Evaluation> getUserSiteEvaluations(String context, int userId) {
    StringBuilder sql;
    Object[] fields;
    int i;

    sql = new StringBuilder();
    sql.append("SELECT e.evaluation_id, e.grade_id, e.user_id, e.sakai_user_id, e.score, e.comments, ");
    sql.append("e.evaluated_by, e.evaluated_date, e.released, e.reviewed_date ");
    sql.append("FROM jforum_evaluations e, jforum_grade g WHERE e.user_id = ? ");
    sql.append("AND e.grade_id = g.grade_id AND g.context = ?");

    fields = new Object[2];
    i = 0;
    fields[i++] = userId;
    fields[i++] = context;

    final List<Evaluation> evaluations = new ArrayList<Evaluation>();

    this.sqlService.dbRead(sql.toString(), fields, new SqlReader() {
        public Object readSqlResultRecord(ResultSet result) {
            try {
                Evaluation evaluation = new EvaluationImpl();
                ((EvaluationImpl) evaluation).setId(result.getInt("evaluation_id"));
                ((EvaluationImpl) evaluation).setGradeId(result.getInt("grade_id"));
                ((EvaluationImpl) evaluation).setUserId(result.getInt("user_id"));
                ((EvaluationImpl) evaluation).setSakaiUserId(result.getString("sakai_user_id"));
                evaluation.setScore(result.getFloat("score"));
                ((EvaluationImpl) evaluation).setEvaluatedBy(result.getInt("evaluated_by"));

                if (result.getDate("evaluated_date") != null) {
                    Timestamp dueDate = result.getTimestamp("evaluated_date");
                    ((EvaluationImpl) evaluation).setEvaluatedDate(dueDate);
                } else {
                    ((EvaluationImpl) evaluation).setEvaluatedDate(null);
                }

                evaluation.setReleased(result.getInt("released") == 1);

                evaluations.add(evaluation);

                return null;
            } catch (SQLException e) {
                if (logger.isWarnEnabled()) {
                    logger.warn("getUserSiteEvaluations: " + e, e);
                }
                return null;
            }
        }
    });

    return evaluations;
}

From source file:org.apache.nifi.util.hive.HiveJdbcCommon.java

public static long convertToAvroStream(final ResultSet rs, final OutputStream outStream, String recordName,
        ResultSetRowCallback callback) throws SQLException, IOException {
    final Schema schema = createSchema(rs, recordName);
    final GenericRecord rec = new GenericData.Record(schema);

    final DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
    try (final DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter)) {
        dataFileWriter.create(schema, outStream);

        final ResultSetMetaData meta = rs.getMetaData();
        final int nrOfColumns = meta.getColumnCount();
        long nrOfRows = 0;
        while (rs.next()) {
            if (callback != null) {
                callback.processRow(rs);
            }/* w  w w .  ja  v  a  2  s  . com*/
            for (int i = 1; i <= nrOfColumns; i++) {
                final int javaSqlType = meta.getColumnType(i);
                Object value = rs.getObject(i);

                if (value == null) {
                    rec.put(i - 1, null);

                } else if (javaSqlType == BINARY || javaSqlType == VARBINARY || javaSqlType == LONGVARBINARY
                        || javaSqlType == BLOB || javaSqlType == CLOB) {
                    // bytes requires little bit different handling
                    ByteBuffer bb = null;
                    if (value instanceof byte[]) {
                        bb = ByteBuffer.wrap((byte[]) value);
                    } else if (value instanceof ByteBuffer) {
                        bb = (ByteBuffer) value;
                    }
                    if (bb != null) {
                        rec.put(i - 1, bb);
                    } else {
                        throw new IOException(
                                "Could not process binary object of type " + value.getClass().getName());
                    }

                } else if (value instanceof Byte) {
                    // tinyint(1) type is returned by JDBC driver as java.sql.Types.TINYINT
                    // But value is returned by JDBC as java.lang.Byte
                    // (at least H2 JDBC works this way)
                    // direct put to avro record results:
                    // org.apache.avro.AvroRuntimeException: Unknown datum type java.lang.Byte
                    rec.put(i - 1, ((Byte) value).intValue());

                } else if (value instanceof BigDecimal || value instanceof BigInteger) {
                    // Avro can't handle BigDecimal and BigInteger as numbers - it will throw an AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38"
                    rec.put(i - 1, value.toString());

                } else if (value instanceof Number) {
                    // Need to call the right getXYZ() method (instead of the getObject() method above), since Doubles are sometimes returned
                    // when the JDBC type is 6 (Float) for example.
                    if (javaSqlType == FLOAT) {
                        value = rs.getFloat(i);
                    } else if (javaSqlType == DOUBLE) {
                        value = rs.getDouble(i);
                    } else if (javaSqlType == INTEGER || javaSqlType == TINYINT || javaSqlType == SMALLINT) {
                        value = rs.getInt(i);
                    }

                    rec.put(i - 1, value);

                } else if (value instanceof Boolean) {
                    rec.put(i - 1, value);
                } else {
                    // The different types that we support are numbers (int, long, double, float),
                    // as well as boolean values and Strings. Since Avro doesn't provide
                    // timestamp types, we want to convert those to Strings. So we will cast anything other
                    // than numbers or booleans to strings by using the toString() method.
                    rec.put(i - 1, value.toString());
                }
            }
            dataFileWriter.append(rec);
            nrOfRows += 1;
        }

        return nrOfRows;
    }
}

From source file:mysql5.MySQL5PlayerDAO.java

@Override
public PlayerCommonData loadPlayerCommonData(final int playerObjId) {

    PlayerCommonData cached = playerCommonData.get(playerObjId);
    if (cached != null) {
        log.debug("[DAO: MySQL5PlayerDAO] PlayerCommonData for id: " + playerObjId + " obtained from cache");
        return cached;
    }//  www.ja  v a2 s  .c  o  m
    final PlayerCommonData cd = new PlayerCommonData(playerObjId);
    boolean success = false;
    Connection con = null;
    try {
        con = DatabaseFactory.getConnection();
        PreparedStatement stmt = con.prepareStatement("SELECT * FROM players WHERE id = ?");
        stmt.setInt(1, playerObjId);
        ResultSet resultSet = stmt.executeQuery();
        log.debug("[DAO: MySQL5PlayerDAO] loading from db " + playerObjId);

        if (resultSet.next()) {
            success = true;
            cd.setName(resultSet.getString("name"));
            // set player class before exp
            cd.setPlayerClass(PlayerClass.valueOf(resultSet.getString("player_class")));
            cd.setExp(resultSet.getLong("exp"));
            cd.setRecoverableExp(resultSet.getLong("recoverexp"));
            cd.setRace(Race.valueOf(resultSet.getString("race")));
            cd.setGender(Gender.valueOf(resultSet.getString("gender")));
            cd.setLastOnline(resultSet.getTimestamp("last_online"));
            cd.setNote(resultSet.getString("note"));
            cd.setQuestExpands(resultSet.getInt("quest_expands"));
            cd.setNpcExpands(resultSet.getInt("npc_expands"));
            cd.setAdvancedStigmaSlotSize(resultSet.getInt("advanced_stigma_slot_size"));
            cd.setTitleId(resultSet.getInt("title_id"));
            cd.setBonusTitleId(resultSet.getInt("bonus_title_id"));
            cd.setWarehouseSize(resultSet.getInt("warehouse_size"));
            cd.setOnline(resultSet.getBoolean("online"));
            cd.setMailboxLetters(resultSet.getInt("mailbox_letters"));
            cd.setDp(resultSet.getInt("dp"));
            cd.setDeathCount(resultSet.getInt("soul_sickness"));
            cd.setCurrentReposteEnergy(resultSet.getLong("reposte_energy"));
            cd.setCurrentEventExp(resultSet.getLong("event_exp"));
            cd.setBattleGroundPoints(resultSet.getInt("bg_points"));

            float x = resultSet.getFloat("x");
            float y = resultSet.getFloat("y");
            float z = resultSet.getFloat("z");
            byte heading = resultSet.getByte("heading");
            int worldId = resultSet.getInt("world_id");
            PlayerInitialData playerInitialData = DataManager.PLAYER_INITIAL_DATA;
            boolean checkThis = World.getInstance().getWorldMap(worldId).isInstanceType();
            // this helps to pretend an player loading error
            // if you have a better idea do it :)
            if (checkThis) {
                mr = null;
            } else {
                mr = World.getInstance().getWorldMap(worldId).getMainWorldMapInstance().getRegion(x, y, z);
            }
            if (mr == null && playerInitialData != null) {
                // unstuck unlucky characters :)
                LocationData ld = playerInitialData.getSpawnLocation(cd.getRace());
                x = ld.getX();
                y = ld.getY();
                z = ld.getZ();
                heading = ld.getHeading();
                worldId = ld.getMapId();
            }

            WorldPosition position = World.getInstance().createPosition(worldId, x, y, z, heading, 0);
            cd.setPosition(position);
            cd.setWorldOwnerId(resultSet.getInt("world_owner"));
            cd.setMentorFlagTime(resultSet.getInt("mentor_flag_time"));
            cd.setInitialGameStats(resultSet.getInt("initial_gamestats"));
            cd.setLastTransferTime(resultSet.getLong("last_transfer_time"));
            cd.setFatigue(resultSet.getInt("fatigue"));
            cd.setFatigueRecover(resultSet.getInt("fatigueRecover"));
            cd.setFatigueReset(resultSet.getInt("fatigueReset"));
            cd.setPassportStamps(resultSet.getInt("stamps"));
            cd.setPassportReward(resultSet.getInt("rewarded_pass"));
            cd.setLastStamp(resultSet.getTimestamp("last_stamp"));
            cd.setJoinRequestLegionId(resultSet.getInt("joinRequestLegionId"));
            cd.setJoinRequestState(LegionJoinRequestState.valueOf(resultSet.getString("joinRequestState")));
        } else {
            log.info("Missing PlayerCommonData from db " + playerObjId);
        }
        resultSet.close();
        stmt.close();
    } catch (Exception e) {
        log.error("Could not restore PlayerCommonData data for player: " + playerObjId + " from DB: "
                + e.getMessage(), e);
    } finally {
        DatabaseFactory.close(con);
    }

    if (success) {
        if (CacheConfig.CACHE_COMMONDATA) {
            playerCommonData.put(playerObjId, cd);
            playerCommonDataByName.put(cd.getName().toLowerCase(), cd);
        }
        return cd;
    }
    return null;
}

From source file:migration.ProjektMigration.java

/**
 * Creates the journalkosten.//ww  w  .j a  v a 2 s. c  o m
 */
public void createJournalkosten() {

    String load_sql;
    Statement load_stmt;
    ResultSet load_rs;

    String store_sql;
    PreparedStatement store_prepstmt;
    final ResultSet store_rs;

    try {

        load_sql = "SELECT IMwStO, IMwStP, IMwStPO, IPreisO, IPreisP, IPreisPO, IWaehrungO, IWaehrungP, IWaehrungPO, OPreisO, OPreisP, OPreisPO, Impact, ImpactDatum, MwStO, MwStP, MwStPO, WaehrungO, WaehrungP, WaehrungPO, Titelnummer FROM ZSTiteltabelle";
        load_stmt = this.leg_con.createStatement();

        store_sql = "INSERT INTO Journalkosten (IMwStO, IMwStP, IMwStPO, IPreisO, IPreisP, IPreisPO, IWaehrungO, IWaehrungP, IWaehrungPO, OPreisO, OPreisP, OPreisPO, impact, impactDatum, mwStO, mwStP, mwStPO, waehrungO, waehrungP, waehrungPO, journal_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        store_prepstmt = this.tgt_con.prepareStatement(store_sql); // evtl.
        // brauchen
        // wir
        // was
        // in
        // Richtung:
        // Statement.RETURN_GENERATED_KEYS

        // logger.info("Lese von ZSTiteltabelle (Journalkosten)");
        load_stmt.execute(load_sql);
        load_rs = load_stmt.getResultSet();

        // logger.info("Schreibe nach Journalkosten");
        while (load_rs.next()) {
            final int titelnummer = load_rs.getInt("Titelnummer");
            final int journalID = this.help.getIdFromIntArray(this.help.getJournals(), titelnummer);
            // ystem.out.println("Titelnummer: " + titelnummer +
            // " JournalID " + journalID);
            if ((titelnummer > 0) && (journalID > 0)) {
                store_prepstmt.setString(1, load_rs.getString("IMwStO"));
                store_prepstmt.setString(2, load_rs.getString("IMwStP"));
                store_prepstmt.setString(3, load_rs.getString("IMwStPO"));
                store_prepstmt.setFloat(4, load_rs.getFloat("IPreisO"));
                store_prepstmt.setFloat(5, load_rs.getFloat("IPreisP"));
                store_prepstmt.setFloat(6, load_rs.getFloat("IPreisPO"));
                store_prepstmt.setString(7, load_rs.getString("IWaehrungO"));
                store_prepstmt.setString(8, load_rs.getString("IWaehrungP"));
                store_prepstmt.setString(9, load_rs.getString("IWaehrungPO"));
                store_prepstmt.setFloat(10, load_rs.getFloat("OPreisO"));
                store_prepstmt.setFloat(11, load_rs.getFloat("OPreisP"));
                store_prepstmt.setFloat(12, load_rs.getFloat("OPreisPO"));
                store_prepstmt.setFloat(13, load_rs.getFloat("Impact"));
                store_prepstmt.setDate(14, load_rs.getDate("ImpactDatum"));
                store_prepstmt.setString(15, load_rs.getString("MwStO"));
                store_prepstmt.setString(16, load_rs.getString("MwStP"));
                store_prepstmt.setString(17, load_rs.getString("MwStPO"));
                store_prepstmt.setString(18, load_rs.getString("WaehrungO"));
                store_prepstmt.setString(19, load_rs.getString("WaehrungP"));
                store_prepstmt.setString(20, load_rs.getString("WaehrungPO"));
                store_prepstmt.setLong(21, journalID);
                store_prepstmt.executeUpdate();
            }
        }

    } catch (final SQLException e) {
        e.printStackTrace(); // To change body of catch statement use File |
                             // Settings | File Templates.
    }

}

From source file:org.apache.gora.sql.store.SqlStore.java

public T readObject(ResultSet rs, T persistent, String[] requestFields) throws SQLException, IOException {
    if (rs == null) {
        return null;
    }//from  w  ww. j a  v a 2s. co  m

    for (int i = 0; i < requestFields.length; i++) {
        String f = requestFields[i];
        Field field = fieldMap.get(f);
        Schema fieldSchema = field.schema();
        Type type = fieldSchema.getType();
        Column column = mapping.getColumn(field.name());
        String columnName = column.getName();
        int columnIndex = rs.findColumn(columnName);

        if (rs.getObject(columnIndex) == null) {
            continue;
        }
        switch (type) {
        case MAP:
            readField(rs, columnIndex, persistent.get(field.pos()), fieldSchema, column);
            break;
        case ARRAY:
            readField(rs, columnIndex, persistent.get(field.pos()), fieldSchema, column);
            break;
        case BOOLEAN:
            persistent.put(field.pos(), rs.getBoolean(columnIndex));
            break;
        case BYTES:
            persistent.put(field.pos(), ByteBuffer.wrap(getBytes(rs, columnIndex, fieldSchema, column)));
            break;
        case DOUBLE:
            persistent.put(field.pos(), rs.getDouble(columnIndex));
            break;
        case ENUM:
            Object val = AvroUtils.getEnumValue(fieldSchema, rs.getString(columnIndex));
            persistent.put(field.pos(), val);
            break;
        case FIXED:
            ((SpecificFixed) persistent.get(i)).bytes(getBytes(rs, columnIndex, fieldSchema, column));
            break;
        case FLOAT:
            persistent.put(field.pos(), rs.getFloat(columnIndex));
            break;
        case INT:
            persistent.put(field.pos(), rs.getInt(columnIndex));
            break;
        case LONG:
            persistent.put(field.pos(), rs.getLong(columnIndex));
            break;
        case NULL:
            break;
        case RECORD:
            Object o = readField(rs, columnIndex, persistent.get(field.pos()), fieldSchema, column);
            persistent.put(field.pos(), o);
            break;
        case STRING:
            persistent.put(field.pos(), new Utf8(rs.getString(columnIndex)));
            break;
        case UNION:
            throw new IOException("Union is not supported yet");
        }
        persistent.setDirty(field.pos());
    }
    persistent.clearDirty();
    return persistent;
}

From source file:se.technipelago.weather.chart.Generator.java

private XYDataset createHistoryDataset(final Date begin, final Date end, final String column,
        final String label) throws SQLException {
    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    PreparedStatement stmt = null;
    ResultSet result = null;
    long spanDays = (end.getTime() - begin.getTime()) / 1000 / 60 / 60 / 24;
    try {//w w w .j a v a  2  s .  c  o m
        final java.sql.Timestamp sqlBegin = new java.sql.Timestamp(begin.getTime());
        final java.sql.Timestamp sqlEnd = new java.sql.Timestamp(end.getTime());
        if (spanDays < 100) {
            stmt = conn.prepareStatement("SELECT ts, " + column + " FROM archive WHERE " + column
                    + " IS NOT NULL AND ts BETWEEN ? AND ? ORDER BY ts");
        } else if (spanDays < 1000) {
            stmt = conn.prepareStatement("SELECT date_format(ts, '%Y-%m-%d %H:00:00') AS day, AVG(" + column
                    + ") AS value FROM archive WHERE " + column
                    + " IS NOT NULL AND ts BETWEEN ? AND ? GROUP BY 1");
        } else {
            stmt = conn.prepareStatement("SELECT date_format(ts, '%Y-%m-%d') AS day, AVG(" + column
                    + ") AS value FROM archive WHERE " + column
                    + " IS NOT NULL AND ts BETWEEN ? AND ? GROUP BY 1");
        }
        stmt.setTimestamp(1, sqlBegin);
        stmt.setTimestamp(2, sqlEnd);
        result = stmt.executeQuery();

        final TimeSeries s1 = new TimeSeries(label, FixedMillisecond.class);
        while (result.next()) {
            final java.sql.Timestamp ts = result.getTimestamp(1);
            final long timestamp = ts.getTime();
            s1.add(new FixedMillisecond(timestamp), result.getFloat(2));
        }
        dataset.addSeries(s1);
    } finally {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                log.log(Level.SEVERE, "Failed to close ResultSet", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                log.log(Level.WARNING, "Failed to close select statement", ex);
            }
        }
    }

    return dataset;
}