Example usage for java.sql ResultSet beforeFirst

List of usage examples for java.sql ResultSet beforeFirst

Introduction

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

Prototype

void beforeFirst() throws SQLException;

Source Link

Document

Moves the cursor to the front of this ResultSet object, just before the first row.

Usage

From source file:org.biblionum.ouvrage.modele.OuvrageTypeModele.java

/**
 * Java method that updates a row in the generated sql table
 *
 * @param con (open java.sql.Connection)
 * @param designation_typeou/*from www. ja  v  a 2 s .c o m*/
 * @return boolean (true on success)
 * @throws SQLException
 */
public boolean updateOuvragetype(DataSource ds, int keyId, String designation_typeou) throws SQLException {
    con = ds.getConnection();
    String sql = "SELECT * FROM ouvragetype WHERE id = ?";
    PreparedStatement statement = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    statement.setInt(1, keyId);
    ResultSet entry = statement.executeQuery();

    entry.last();
    int rows = entry.getRow();
    entry.beforeFirst();
    if (rows == 0) {
        entry.close();
        statement.close();
        con.close();
        return false;
    }
    entry.next();

    if (designation_typeou != null) {
        entry.updateString("designation_typeou", designation_typeou);
    }

    entry.updateRow();
    entry.close();
    statement.close();
    con.close();
    return true;
}

From source file:de.static_interface.reallifeplugin.module.contract.database.table.ContractUserOptionsTable.java

@Override
public ContractUserOptionsRow[] deserialize(ResultSet rs) throws SQLException {
    int rowcount = 0;
    if (rs.last()) {
        rowcount = rs.getRow();//from  w  w  w  . ja  va 2  s.  c o m
        rs.beforeFirst();
    }

    ContractUserOptionsRow[] rows = new ContractUserOptionsRow[rowcount];
    int i = 0;

    while (rs.next()) {
        ContractUserOptionsRow row = new ContractUserOptionsRow();
        if (hasColumn(rs, "id")) {
            row.id = rs.getInt("id");
        }
        if (hasColumn(rs, "user_id")) {
            row.userId = rs.getInt("userId");
        }
        if (hasColumn(rs, "contract_id")) {
            row.contractId = rs.getInt("contract_id");
        }
        if (hasColumn(rs, "isCreator")) {
            row.isCreator = rs.getBoolean("isCreator");
        }
        if (hasColumn(rs, "money")) {
            row.money = rs.getDouble("money");
            if (rs.wasNull()) {
                row.money = null;
            }
        }
        rows[i] = row;
        i++;
    }
    return rows;
}

From source file:de.static_interface.reallifeplugin.module.corporation.database.table.CorpsTable.java

@Override
public CorpRow[] deserialize(ResultSet rs) throws SQLException {
    int rowcount = 0;
    if (rs.last()) {
        rowcount = rs.getRow();/*  ww w. j av a 2  s .  c om*/
        rs.beforeFirst();
    }

    CorpRow[] rows = new CorpRow[rowcount];
    int i = 0;

    while (rs.next()) {
        CorpRow row = new CorpRow();
        if (hasColumn(rs, "id")) {
            row.id = rs.getInt("id");
        }
        if (hasColumn(rs, "balance")) {
            row.balance = rs.getDouble("balance");
        }
        if (hasColumn(rs, "base_id")) {
            row.baseId = rs.getString("base_id");
        }
        if (hasColumn(rs, "base_world")) {
            row.baseWorld = rs.getString("base_world");
        }
        if (hasColumn(rs, "ceo_uuid")) {
            row.ceoUniqueId = UUID.fromString(rs.getString("ceo_uuid"));
        }
        if (hasColumn(rs, "corp_name")) {
            row.corpName = rs.getString("corp_name");
        }
        if (hasColumn(rs, "isdeleted")) {
            row.isDeleted = rs.getBoolean("isdeleted");
        }
        if (hasColumn(rs, "tag")) {
            row.tag = rs.getString("tag");
        }
        if (hasColumn(rs, "time")) {
            row.time = rs.getLong("time");
        }
        rows[i] = row;
        i++;
    }
    return rows;
}

From source file:com.autentia.tnt.bill.migration.support.OriginalInformationRecoverer.java

/**
 * Recupera la suma total de todos los conceptos de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura/*from ww w  .ja va 2s .co m*/
 */
public static double[] getImporteFacturaOriginal(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    double[] result = new double[0];

    try {
        log.info("RECOVERING IMPORTE FACTURAS " + billType + " ORIGINALES");

        // connect to database
        Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER);
        con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION,
                BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); //NOSONAR
        con.setAutoCommit(false); //DATABASE_PASS vacio.            

        String sql = "SELECT sum((bb.units*bb.amount)*(1+(bb.iva/100))) as total from Bill b left join BillBreakDown bb on b.id=bb.billId, Organization o, Project p where b.projectId = p.id and p.organizationId = o.id and b.billType= ? group by b.id order by total";

        pstmt = con.prepareStatement(sql);

        rs = pstmt.executeQuery();
        pstmt.setString(1, billType);

        rs.last();
        result = new double[rs.getRow()];
        rs.beforeFirst();
        int counter = 0;

        while (rs.next()) {
            result[counter] = rs.getDouble(1);
            log.info("\t" + result[counter]);
            counter++;
        }
        con.commit();
    } catch (Exception e) {
        log.error("FAILED: WILL BE ROLLED BACK: ", e);
        if (con != null) {
            con.rollback();
        }
    } finally {
        cierraFichero(file);
        liberaConexion(con, pstmt, rs);
    }
    return result;
}

From source file:org.biblionum.authentification.modele.UtilisateurModele.java

/**
 * Java method that updates a row in the generated sql table
 *
 * @param con (open java.sql.Connection)
 * @param nom/* ww w .j  a  va  2 s .  c  o  m*/
 * @param password
 * @param pseudo
 * @param prenom
 * @param utilisateur_type_id
 * @return boolean (true on success)
 * @throws SQLException
 */
public boolean updateUtilisateur(DataSource ds, int keyId, String nom, String password, String pseudo,
        String prenom) throws SQLException {
    con = ds.getConnection();
    String sql = "SELECT * FROM utilisateur WHERE id = ?";
    PreparedStatement statement = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    statement.setInt(1, keyId);
    ResultSet entry = statement.executeQuery();

    entry.last();
    int rows = entry.getRow();
    entry.beforeFirst();
    if (rows == 0) {
        entry.close();
        statement.close();
        con.close();
        return false;
    }
    entry.next();

    if (nom != null) {
        entry.updateString("nom", nom);
    }
    if (password != null) {
        entry.updateString("password", password);
    }
    if (pseudo != null) {
        entry.updateString("pseudo", pseudo);
    }
    if (prenom != null) {
        entry.updateString("prenom", prenom);
    }

    entry.updateRow();
    entry.close();
    statement.close();
    con.close();
    return true;
}

From source file:org.openmrs.module.databasebackup.util.DbDump.java

/** Dump the whole database to an SQL string */
public static void dumpDB(Properties props, boolean showProgress, Class showProgressToClass) throws Exception {
    String filename = props.getProperty("filename");
    String folder = props.getProperty("folder");
    String driverClassName = props.getProperty("driver.class");
    String driverURL = props.getProperty("driver.url");
    DatabaseMetaData dbMetaData = null;
    Connection dbConn = null;// ww  w .  j  a va2  s  .  c om

    Class.forName(driverClassName);
    dbConn = DriverManager.getConnection(driverURL, props);
    dbMetaData = dbConn.getMetaData();

    FileOutputStream fos = new FileOutputStream(folder + filename);
    OutputStreamWriter result = new OutputStreamWriter(fos, fileEncoding);

    String catalog = props.getProperty("catalog");
    String schema = props.getProperty("schemaPattern");

    String tablesIncluded = props.getProperty("tables.included");
    List<String> tablesIncludedVector = Arrays.asList(tablesIncluded.split(","));

    String tablesExcluded = props.getProperty("tables.excluded");
    List<String> tablesExcludedVector = Arrays.asList(tablesExcluded.split(","));

    ResultSet rs = dbMetaData.getTables(catalog, schema, null, null);
    int progressCnt = 0;

    log.debug("tablesIncluded: " + tablesIncluded);
    log.debug("tablesExcluded: " + tablesExcluded);

    result.write("/*\n" + " * DB jdbc url: " + driverURL + "\n" + " * Database product & version: "
            + dbMetaData.getDatabaseProductName() + " " + dbMetaData.getDatabaseProductVersion() + "\n"
            + " */");

    result.write("\nSET FOREIGN_KEY_CHECKS=0;\n");

    List<String> tableVector = new Vector<String>();
    int progressTotal = 0;
    while (rs.next()) {
        String tableName = rs.getString("TABLE_NAME");
        if ((tablesIncluded.contains("all") && !tablesExcludedVector.contains(tableName)
                || tablesIncluded.contains(tableName))
                || (tablesExcludedVector.contains("none") && !tablesIncludedVector.contains("none"))) {
            progressTotal++;
            tableVector.add(tableName);
        }
    }
    rs.beforeFirst();

    if (!rs.next()) {
        log.error("Unable to find any tables matching: catalog=" + catalog + " schema=" + schema + " tables="
                + tableVector.toArray().toString());
        rs.close();
    } else {
        do {
            String tableName = rs.getString("TABLE_NAME");
            String tableType = rs.getString("TABLE_TYPE");

            if (tableVector.contains(tableName)) {

                progressCnt++;
                //BackupFormController.getProgressInfo().put(filename, "Backing up table " + progressCnt + " of " + progressTotal + " (" + tableName + ")...");

                if (showProgress) {
                    Map<String, String> info = (Map<String, String>) showProgressToClass
                            .getMethod("getProgressInfo", null).invoke(showProgressToClass);
                    info.put(filename, "Backing up table " + progressCnt + " of " + progressTotal + " ("
                            + tableName + ")...");
                    showProgressToClass.getMethod("setProgressInfo", new Class[] { Map.class })
                            .invoke(showProgressToClass, info);
                }

                if ("TABLE".equalsIgnoreCase(tableType)) {

                    result.write("\n\n-- Structure for table `" + tableName + "`\n");
                    result.write("DROP TABLE IF EXISTS `" + tableName + "`;\n");

                    PreparedStatement tableStmt = dbConn
                            .prepareStatement("SHOW CREATE TABLE " + tableName + ";");
                    ResultSet tablesRs = tableStmt.executeQuery();
                    while (tablesRs.next()) {
                        result.write(tablesRs.getString("Create Table") + ";\n\n");
                    }
                    tablesRs.close();
                    tableStmt.close();

                    dumpTable(dbConn, result, tableName);
                    System.gc();
                }
            }
        } while (rs.next());
        rs.close();
    }

    result.write("\nSET FOREIGN_KEY_CHECKS=1;\n");

    result.flush();
    result.close();

    dbConn.close();
}

From source file:org.biblionum.ouvrage.modele.OuvrageModele.java

/**
 * Java method that updates a row in the generated sql table
 *
 * @param con (open java.sql.Connection)
 * @param auteur//from   w  w  w.j av  a 2s.  c  o  m
 * @param editeur
 * @param annee_edition
 * @param resume
 * @param nb_page
 * @param emplacement
 * @param couverture
 * @param ouvrageTipeid
 * @param categorieOuvrageid
 * @param niveauid_niveau
 * @param filiereid
 * @param titre
 * @return boolean (true on success)
 * @throws SQLException
 */
public boolean updateUtilisateur(DataSource ds, int keyId, String auteur, String editeur, int annee_edition,
        String resume, int nb_page, String emplacement, String couverture, int ouvrageTipeid,
        int categorieOuvrageid, int niveauid_niveau, int filiereid, String titre) throws SQLException {
    con = ds.getConnection();
    String sql = "SELECT * FROM ouvrage WHERE id = ?";
    PreparedStatement statement = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    statement.setInt(1, keyId);
    ResultSet entry = statement.executeQuery();

    entry.last();
    int rows = entry.getRow();
    entry.beforeFirst();
    if (rows == 0) {
        entry.close();
        statement.close();
        con.close();
        return false;
    }
    entry.next();

    if (auteur != null) {
        entry.updateString("auteur", auteur);
    }
    if (editeur != null) {
        entry.updateString("editeur", editeur);
    }
    entry.updateInt("annee_edition", annee_edition);
    if (resume != null) {
        entry.updateString("resume", resume);
    }
    entry.updateInt("nb_page", nb_page);
    if (emplacement != null) {
        entry.updateString("emplacement", emplacement);
    }
    if (couverture != null) {
        entry.updateString("couverture", couverture);
    }
    entry.updateInt("ouvrageTipeid", ouvrageTipeid);
    entry.updateInt("categorieOuvrageid", categorieOuvrageid);
    entry.updateInt("niveauid_niveau", niveauid_niveau);
    entry.updateInt("filiereid", filiereid);
    if (titre != null) {
        entry.updateString("titre", titre);
    }

    entry.updateRow();
    entry.close();
    statement.close();
    con.close();
    return true;
}

From source file:com.laxser.blitz.lama.provider.jdbc.PreparedStatementCallbackReturnId.java

@Override
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {

    if (setter != null) {
        setter.setValues(ps);//from   ww  w.j  a  v a  2 s .c om
    }

    int updated = ps.executeUpdate();
    if (updated == 0) {
        if (returnType.isArray()) {
            return Array.newInstance(wrappedIdType, 0);
        } else {
            return defaultValueOf(wrappedIdType);
        }
    }

    ResultSet keys = ps.getGeneratedKeys();
    if (keys != null) {
        try {
            Object ret = null;
            if (returnType.isArray()) {
                keys.last();
                int length = keys.getRow();
                keys.beforeFirst();
                ret = Array.newInstance(wrappedIdType, length);
            }

            for (int i = 0; keys.next(); i++) {
                Object value = mapper.mapRow(keys, i);
                if (value == null && idType.isPrimitive()) {
                    // ?primitive??null??
                    value = defaultValueOf(wrappedIdType);
                }
                if (ret != null) {
                    Array.set(ret, i + 1, value);
                } else {
                    ret = value;
                    break;
                }
            }
            return ret;
        } finally {
            JdbcUtils.closeResultSet(keys);
        }
    } else {
        if (returnType.isArray()) {
            return Array.newInstance(wrappedIdType, 0);
        } else {
            return defaultValueOf(wrappedIdType);
        }
    }
}

From source file:org.owasp.webgoat.plugin.CrossSiteScriptingLesson5b.java

public String writeTable(ResultSet results, ResultSetMetaData resultsMetaData)
        throws IOException, SQLException {
    int numColumns = resultsMetaData.getColumnCount();
    results.beforeFirst();
    StringBuffer t = new StringBuffer();
    t.append("<p>");

    if (results.next()) {
        for (int i = 1; i < (numColumns + 1); i++) {
            t.append(resultsMetaData.getColumnName(i));
            t.append(", ");
        }//from   www. j  av a 2  s . c  om

        t.append("<br />");
        results.beforeFirst();

        while (results.next()) {

            for (int i = 1; i < (numColumns + 1); i++) {
                t.append(results.getString(i));
                t.append(", ");
            }

            t.append("<br />");
        }

    } else {
        t.append("Query Successful; however no data was returned from this query.");
    }

    t.append("</p>");
    return (t.toString());
}

From source file:com.mongosqlmigrator.harsha.sql.DocBuilder.java

private void getMultiValuedEntity(ResultSet rs, Entity entity, Map<String, Object> rootEntityMap)
        throws SQLException {
    List<Object> fieldArray = new ArrayList<Object>();
    rs.beforeFirst();
    while (rs.next()) {
        if (entity.fields.size() > 1) {
            Map<String, Object> entityFieldsMap = new HashMap<String, Object>();
            for (Iterator<Field> iterator = entity.fields.iterator(); iterator.hasNext();) {
                Field field = iterator.next();
                FieldType fieldType = FieldType.valueOf(field.allAttributes.get("type").toUpperCase());
                entityFieldsMap.put(field.name, convertFieldType(fieldType, rs.getObject(field.column)).get(0));
            }//from w w  w.  j a  va  2  s . c o  m
            fieldArray.add(entityFieldsMap);
        } else if (entity.fields.size() == 1) {
            fieldArray.add(rs.getObject(entity.fields.get(0).column));
        }
    }
    rootEntityMap.put(entity.name, fieldArray);
}