Example usage for java.sql ResultSet next

List of usage examples for java.sql ResultSet next

Introduction

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

Prototype

boolean next() throws SQLException;

Source Link

Document

Moves the cursor forward one row from its current position.

Usage

From source file:com.nabla.dc.server.handler.fixed_asset.Asset.java

static public void dispose(final Connection conn, final Integer assetId, final IDisposal disposal)
        throws SQLException, DispatchException {
    final PreparedStatement redo = conn
            .prepareStatement("INSERT INTO fa_transaction_redo (fa_asset_id, command) VALUES(?,?);");
    try {/*  w w  w  . ja va  2 s .  c o m*/
        redo.setInt(1, assetId);
        // backup transaction after disposal if any
        if (log.isDebugEnabled())
            log.debug("backing up transactions after disposal date");
        // charge monthly depreciation in disposal month if disposal is after 15
        final Calendar dt = Util.dateToCalendar(disposal.getDate());
        if (dt.get(GregorianCalendar.DAY_OF_MONTH) >= dt.getActualMaximum(GregorianCalendar.DAY_OF_MONTH) / 2)
            dt.add(GregorianCalendar.MONTH, 1);
        dt.set(GregorianCalendar.DAY_OF_MONTH, 1);
        final Date from = Util.calendarToSqlDate(dt);
        // get list of transactions to backup before we delete them
        final IntegerSet transIds = new IntegerSet();
        final PreparedStatement stmt = StatementFormat.prepare(conn,
                "SELECT t.*" + " FROM fa_transaction AS t INNER JOIN period_end AS p ON t.period_end_id=p.id"
                        + " WHERE t.fa_asset_id=? AND p.end_date>?;",
                assetId, from);
        try {
            final ResultSet rs = stmt.executeQuery();
            try {
                while (rs.next()) {
                    transIds.add(rs.getInt("id"));
                    final String command = MessageFormat.format("INSERT INTO fa_transaction"
                            + " (id,fa_asset_id,period_end_id,amount,class,type,depreciation_period)"
                            + " VALUES({0,number,0},{1,number,0},{2,number,0},{3,number,0},''{4}'',''{5}'',{6,number,0});",
                            rs.getInt("id"), rs.getInt("fa_asset_id"), rs.getInt("period_end_id"),
                            rs.getInt("amount"), rs.getString("class"), rs.getString("type"),
                            Database.getInteger(rs, "depreciation_period"));
                    if (log.isTraceEnabled())
                        log.trace("redo = " + command);
                    redo.setString(2, command);
                    redo.addBatch();
                }
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
        // remove any transaction after disposal date
        if (log.isDebugEnabled())
            log.debug("removing transactions after disposal date");
        Database.executeUpdate(conn, "DELETE FROM fa_transaction WHERE id IN (?);", transIds);
        // add disposal transactions
        if (log.isDebugEnabled())
            log.debug("adding transactions for disposal");
        final TransactionList transactions = new TransactionList(assetId);
        // closing cost
        transactions.add(new Transaction(TransactionClasses.COST, TransactionTypes.CLOSING, disposal.getDate(),
                -1 * getAssetCostBeforeDisposal(conn, assetId)));
        // closing accumulated depreciation
        transactions.add(new Transaction(TransactionClasses.DEP, TransactionTypes.CLOSING, disposal.getDate(),
                -1 * getAssetDepreciationBeforeDisposal(conn, assetId)));
        for (Integer newTransId : transactions.save(conn, true)) {
            redo.setString(2,
                    MessageFormat.format("DELETE FROM fa_transaction WHERE id={0,number,0};", newTransId));
            redo.addBatch();
        }
        if (!Database.isBatchCompleted(redo.executeBatch()))
            throw new InternalErrorException("failed to save disposal transactions");
    } finally {
        redo.close();
    }
}

From source file:libepg.util.db.AboutDB.java

/**
 * ???????? ?????// www.jav a 2s  .com
 *
 * @param conn ??DB??
 * @return ?
 * @throws java.sql.SQLException
 * @see libepg.util.db.AboutDB#CRATE_TABLE
 */
public static synchronized List<TsPacket> convertToList(Connection conn) throws SQLException {
    final String DUMP = "SELECT " + PACKET + " FROM " + TABLE_NAME + " ORDER BY number ASC";
    ResultSet rs = conn.createStatement().executeQuery(DUMP);

    //?
    List<TsPacket> packets = new ArrayList<>();
    while (rs.next()) {
        TsPacket tsp = new TsPacket(rs.getBytes(PACKET));
        packets.add(tsp);
    }
    return packets;
}

From source file:dsd.dao.ParsedInputFilesDAO.java

public static long GetMaxTimestamp(eFileType fileType) {
    long timestamp = 0;
    try {//from  ww w  .  j a v a  2s.c  o  m
        Connection con = DAOProvider.getDataSource().getConnection();
        try {
            Object[] parameters = new Object[1];
            parameters[0] = new Integer(fileType.getCode());
            ResultSet results = DAOProvider.SelectTableSecure(tableName, " max(timestamp) ", " type = ? ", "",
                    con, parameters);
            while (results.next()) {
                timestamp = results.getTimestamp(1).getTime();
            }
        } catch (Exception exc) {
            //            exc.printStackTrace();
            timestamp = 0;
        }
        con.close();
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    return timestamp;
}

From source file:dsd.dao.WorstCaseDAO.java

public static long GetCount(boolean traffic, boolean debris) {
    long count = 0;
    try {/*from w w w  .  j  av  a 2  s .  c o  m*/
        Connection con = DAOProvider.getDataSource().getConnection();
        try {
            String tableName = GetTableNameForDataType(traffic, debris);
            ResultSet results = DAOProvider.SelectTableSecure(tableName, " count(*) ", "", "", con, null);
            while (results.next()) {
                count = results.getLong(1);
            }
        } catch (Exception exc) {
            exc.printStackTrace();
        }
        con.close();
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    return count;
}

From source file:edu.mayo.cts2.uriresolver.dao.DAOUtiltities.java

public static boolean tableExists(DatabaseMetaData metaData, String tablename) {
    //ResultSet tables = metaData.getTables(null, "public", "%" ,new String[] {"TABLE"} );
    ResultSet tables = null;
    try {//from  w ww.ja  va2 s . c  o  m
        tables = metaData.getTables(null, null, tablename, null);
        if (tables.next()) {
            tables.close();
            return true;
        }
    } catch (SQLException e) {
        return false;
    } finally {
        if (tables != null) {
            try {
                tables.close();
            } catch (SQLException e1) {
                logger.error("Error while colsing result set: " + e1.getMessage());
            }
        }
    }

    return false;
}

From source file:com.sql.SystemErrorEmailList.java

/**
 * Gathers a list of active email addresses to send to for the email
 * for the daily crash report email.//from  ww w  .  j av  a 2s .  c om
 * 
 * @return
 */
public static List<String> getActiveEmailAddresses() {
    List<String> list = new ArrayList();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT EmailAddress " + "FROM SystemErrorEmailList " + "WHERE active = 1";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            if (rs.getString("EmailAddress") != null) {
                list.add(rs.getString("EmailAddress"));
            }
        }
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return list;
}

From source file:com.sql.SystemEmail.java

/**
 * Gathers active email accounts for sending or receiving. 
 * /*from w  w w . j a v  a2  s  .  co m*/
 * @return
 */
public static boolean loadEmailConnectionInformation() {
    List<SystemEmailModel> systemEmailList = new ArrayList();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT * FROM SystemEmail WHERE active = 1";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            SystemEmailModel row = new SystemEmailModel();
            row.setId(rs.getInt("id"));
            row.setActive(rs.getInt("active"));
            row.setSection(rs.getString("section"));
            row.setEmailAddress(rs.getString("emailAddress"));
            row.setUsername(rs.getString("username"));
            row.setPassword(rs.getString("password"));
            row.setIncomingURL(rs.getString("incomingURL"));
            row.setIncomingPort(rs.getInt("incomingPort"));
            row.setIncomingProtocol(rs.getString("incomingProtocol"));
            row.setIncomingFolder(rs.getString("incomingFolder"));
            row.setOutgoingURL(rs.getString("outgoingURL"));
            row.setOutgoingPort(rs.getInt("outgoingPort"));
            row.setOutgoingProtocol(rs.getString("outgoingProtocol"));
            row.setOutgoingFolder(rs.getString("outgoingFolder"));
            systemEmailList.add(row);
        }
        Global.setSystemEmailParams(systemEmailList);
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
        return false;
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return true;
}

From source file:application.bbdd.pool.java

public static void realizaConsulta2() {
    Connection conexion = null;/*from w  w w .  jav a2s.  c o m*/
    Statement sentencia = null;
    ResultSet rs = null;

    try {
        conexion = getConexion();
        sentencia = conexion.createStatement();
        rs = sentencia.executeQuery("select count(*) from db");
        rs.next();
        JOptionPane.showMessageDialog(null, "El numero de bd es: " + rs.getInt(1));
        logStatistics();

    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, e.toString());
    } finally {
        try {
            rs.close();
            sentencia.close();
            liberaConexion(conexion);
        } catch (Exception fe) {
            JOptionPane.showMessageDialog(null, fe.toString());
        }
    }
}

From source file:com.bluepandora.therap.donatelife.adminpanel.JsonBuilder.java

public static JSONObject getAdminListJson(ResultSet result) throws JSONException {
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject;/*from   w  w  w  .  j a  v  a  2  s  .  c om*/
    try {
        while (result.next()) {
            jsonObject = new JSONObject();
            jsonObject.put(jsFirstName, result.getString(dbFirstName));
            jsonObject.put(jsLastName, result.getString(dbLastName));
            jsonObject.put(jsMobileNumber, result.getString(dbMobileNumber));
            jsonObject.put(jsEmail, result.getString(dbEmail));
            jsonArray.put(jsonObject);
        }
        jsonObject = new JSONObject();
        jsonObject.put(jsAdminList, jsonArray);
        jsonObject.put(jsDONE, 1);
    } catch (SQLException error) {
        Debug.debugLog("ADMIN RESULT SET: ", error);
        jsonObject = new JSONObject();
        jsonObject.put(jsDONE, 0);
    }
    return jsonObject;
}

From source file:com.data2semantics.yasgui.server.db.ConnectionFactory.java

/**
 * Check if database exists//from   w w w.ja  va  2 s.  com
 * @param connect
 * @param dbName
 * @return
 * @throws SQLException
 */
private static boolean databaseExists(Connection connect, String dbName) throws SQLException {
    Statement statement = connect.createStatement();
    ResultSet resultSet = statement.executeQuery(
            "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" + dbName + "'");
    boolean exists = resultSet.next();
    statement.close();
    resultSet.close();
    return exists;
}