Example usage for java.sql ResultSet isBeforeFirst

List of usage examples for java.sql ResultSet isBeforeFirst

Introduction

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

Prototype

boolean isBeforeFirst() throws SQLException;

Source Link

Document

Retrieves whether the cursor is before the first row in this ResultSet object.

Usage

From source file:me.eccentric_nz.plugins.FatPort.FatPortCmdUtils.java

public boolean hasCommand(int pid) {
    boolean bool = false;
    try {/*  w w w .  j a va2s . c  o  m*/
        Connection connection = service.getConnection();
        Statement statement = connection.createStatement();
        String queryCmd = "SELECT c_id FROM commands WHERE p_id = " + pid;
        ResultSet rsCmd = statement.executeQuery(queryCmd);
        if (rsCmd.isBeforeFirst()) {
            bool = true;
        }
        rsCmd.close();
        statement.close();
    } catch (SQLException e) {
        plugin.debug("Could not check for command! " + e);
    }
    return bool;
}

From source file:at.becast.youploader.youtube.playlists.PlaylistManager.java

public void load() {
    if (playlists.isEmpty()) {
        Connection c = SQLite.getInstance();
        Statement stmt;//from   ww w  . j  a  v a 2  s .c  o  m
        try {
            stmt = c.createStatement();
            String sql = "SELECT * FROM `playlists`";
            ResultSet rs = stmt.executeQuery(sql);
            if (rs.isBeforeFirst()) {
                while (rs.next()) {
                    String shown;
                    if (rs.getString("shown") == null) {
                        shown = "1";
                        SQLite.setPlaylistHidden(rs.getInt("id"), shown);
                    } else {
                        shown = rs.getString("shown");
                    }
                    Playlist l = new Playlist(rs.getInt("id"), rs.getString("playlistid"), rs.getString("name"),
                            rs.getBytes("image"), shown);
                    if (playlists.get(rs.getInt("account")) == null) {
                        List<Playlist> list = new ArrayList<Playlist>();
                        list.add(l);
                        playlists.put(rs.getInt("account"), list);
                    } else {
                        playlists.get(rs.getInt("account")).add(l);
                    }
                }
                rs.close();
                stmt.close();
            } else {
                rs.close();
                stmt.close();
            }
        } catch (SQLException e) {
            LOG.error("Error loading playlists", e);
        }
    }
}

From source file:org.ensembl.healthcheck.testcase.funcgen.MetaCoord.java

/**
 * Run the test.//www  .  j  a  v  a 2  s  . c om
 * 
 * @param funcgenDbre
 *          The database to use.
 * @return true if the test passed.
 * 
 */
public boolean run(DatabaseRegistryEntry funcgenDbre) {

    boolean result = true;

    DatabaseRegistryEntry coreDbre;

    try {

        coreDbre = getCoreDb(funcgenDbre);

    } catch (MissingMetaKeyException e) {

        ReportManager.problem(this, funcgenDbre.getConnection(), e.getMessage());
        return false;

    } catch (CoreDbNotFoundException e) {

        ReportManager.problem(this, funcgenDbre.getConnection(), e.getMessage());
        return false;

    }

    Connection funcgenCon = funcgenDbre.getConnection();
    Connection coreCon = coreDbre.getConnection();

    // coordSystems is a hash of lists of coordinate systems that each feature
    // table contains
    Map coordSystems = new HashMap();

    try {

        Statement funcgenStatement = funcgenCon.createStatement();
        Statement coreStatement = coreCon.createStatement();

        // build up a list of all the coordinate systems that are in the various
        // feature tables
        for (int tableIndex = 0; tableIndex < featureTables.length; tableIndex++) {

            String tableName = featureTables[tableIndex];
            String funcgenSql = "SELECT DISTINCT(seq_region_id) FROM " + tableName;

            logger.finest("Getting seq_region_ids for " + tableName);
            ResultSet funcgenRs = funcgenStatement.executeQuery(funcgenSql);

            ArrayList<String> seqRegionIDs = new ArrayList<>();

            if (!funcgenRs.isBeforeFirst()) {
                logger.warning("No features found for " + tableName);
                continue;
            }

            if (funcgenRs.next())
                while (funcgenRs.next()) {
                    seqRegionIDs.add(funcgenRs.getString(1));
                }

            String seqRegionIDsString = seqRegionIDs.toString().replace("[", "").replace("]", "");
            String coreSql = "SELECT DISTINCT(coord_system_id) FROM seq_region WHERE seq_region_id IN ("
                    + seqRegionIDsString + ")";
            logger.finest("Getting coord_system_ids for " + tableName);
            ResultSet coreRs = coreStatement.executeQuery(coreSql);

            while (coreRs.next()) {
                String coordSystemID = coreRs.getString(1);
                logger.finest("Added feature coordinate system for " + tableName + ": " + coordSystemID);
                // check that the meta_coord table has an entry corresponding to this
                int mc = DBUtils.getRowCount(funcgenCon,
                        "SELECT COUNT(*) FROM meta_coord WHERE coord_system_id=" + coordSystemID
                                + " AND table_name='" + tableName + "'");
                if (mc == 0) {
                    ReportManager.problem(this, funcgenCon, "No entry for coordinate system with ID "
                            + coordSystemID + " for " + tableName + " in meta_coord");
                    result = false;
                } else if (mc > 1) {
                    ReportManager.problem(this, funcgenCon, "Coordinate system with ID " + coordSystemID
                            + " duplicated for " + tableName + " in meta_coord");
                    result = false;
                } else {
                    ReportManager.correct(this, funcgenCon, "Coordinate system with ID " + coordSystemID
                            + " for table " + tableName + " has an entry in meta_coord");
                }

                // store in coordSystems map - create List if necessary
                List csList = (ArrayList) coordSystems.get(tableName);
                if (csList == null) {
                    csList = new ArrayList();
                }
                csList.add(coordSystemID);
                coordSystems.put(tableName, csList);
            }

            funcgenRs.close();

        }

        // check that every meta_coord table entry refers to a coordinate system
        // that is used in a feature
        // if this isn't true it's not fatal but should be flagged
        String sql = "SELECT * FROM meta_coord";
        ResultSet rs = funcgenStatement.executeQuery(sql);
        while (rs.next()) {
            String tableName = rs.getString("table_name");
            String csID = rs.getString("coord_system_id");
            logger.finest("Checking for coord_system_id " + csID + " in " + tableName);
            List featureCSs = (ArrayList) coordSystems.get(tableName);
            if (featureCSs != null && !featureCSs.contains(csID)) {
                ReportManager.problem(this, funcgenCon,
                        "meta_coord has entry for coord_system ID " + csID + " in " + tableName
                                + " but this coordinate system is not actually used in " + tableName);
                result = false;
            }

        }

        rs.close();
        funcgenStatement.close();

        // check that there are no null max_length entries
        result &= checkNoNulls(funcgenCon, "meta_coord", "max_length");

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return result;

}

From source file:com.egt.core.db.util.Exporter.java

private static ExporterMessage export(String informe, Long rastro, Long usuario, String destino,
        EnumFormatoArchivo tipo, String select, Object[] args, boolean logging) {
    Bitacora.trace(Exporter.class, "export", informe, rastro, destino, tipo);
    Bitacora.trace(trimToDefaultSelect(select));
    Utils.traceObjectArray(args);//from  w ww .  j  a v  a2 s  .co m
    String report = StringUtils.trimToEmpty(informe);
    String target = trimToNullTarget(destino);
    String format = getExportFormat(tipo);
    ResultSet resultSet = null;
    //      String archivo = logging ? getLogFileName(rastro) : null;
    String archivo = null;
    EnumCondicionEjeFun condicion = EnumCondicionEjeFun.EJECUCION_EN_PROGRESO;
    String mensaje = TLC.getBitacora().info(CBM2.EXPORT_EXECUTION_BEGIN, report);
    boolean ok = Auditor.grabarRastroInforme(rastro, condicion, archivo, mensaje);
    if (ok) {
        try {
            JasperReport jasperReport = Reporter.getJasperReport(report);
            select = jasperReport == null ? select
                    : Utils.replaceWhereClause(jasperReport.getQuery().getText(), select);
            if (StringUtils.isBlank(select)) {
                condicion = EnumCondicionEjeFun.EJECUTADO_CON_ERRORES;
                mensaje = TLC.getBitacora().error(CBM2.ERROR_COMANDO_SELECT);
            } else {
                int limite = Reporter.getLimiteFilasFuncionSelect(report);
                resultSet = TLC.getAgenteSql().executeQuery(select, limite, args);
                if (resultSet.isBeforeFirst()) {
                    archivo = export(resultSet, report, target, format, usuario);
                    condicion = EnumCondicionEjeFun.EJECUTADO_SIN_ERRORES;
                    mensaje = TLC.getBitacora().warn(CBM2.EXPORT_EXECUTION_END, report);
                } else {
                    condicion = EnumCondicionEjeFun.EJECUTADO_SIN_ERRORES;
                    mensaje = TLC.getBitacora().error(CBM2.SELECT_ROW_EMPTY_SET, report);
                }
            }
        } catch (Exception ex) {
            condicion = EnumCondicionEjeFun.EJECUTADO_CON_ERRORES;
            mensaje = ThrowableUtils.getString(ex);
            TLC.getBitacora().fatal(ex);
            TLC.getBitacora().fatal(CBM2.EXPORT_EXECUTION_ABEND, report);
        } finally {
            Auditor.grabarRastroInforme(rastro, condicion, archivo, mensaje);
            DB.close(resultSet);
        }
    } else {
        condicion = EnumCondicionEjeFun.EJECUCION_CANCELADA;
        mensaje = TLC.getBitacora().error(CBM2.PROCESS_EXECUTION_ABEND, report);
    }
    ExporterMessage message = new ExporterMessage(report);
    message.setDestino(target);
    message.setTipo(tipo);
    message.setSelect(select);
    message.setArgs(args);
    message.setRastro(rastro);
    message.setCondicion(condicion);
    message.setArchivo(archivo);
    message.setMensaje(mensaje);
    return message;
}

From source file:net.certifi.audittablegen.PostgresqlDMR.java

/**
 * Get List of ColumnDef objects for all tables
 * in the targeted database/schema.  Postgres specific code replaces 
 * 'serial' date type with integer, because the column in the audit table
 * must be of type integer and not serial.  Since this data is interpreted
 * by ChangeSourceFactory, which should be database independent, the
 * translation needs to be in the DMR.//  w  w w  . java 2 s . c  om
 * 
 * @param tableName
 * @return ArrayList of ColumnDef objects or an empty list if none are found.
 */
@Override
public List getColumns(String tableName) {

    //getDataTypes will initialize the map if it isn't already loaded
    Map<String, DataTypeDef> dtds = getDataTypes();

    List columns = new ArrayList<>();

    try {
        Connection conn = dataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        ResultSet rs = dmd.getColumns(null, verifiedSchema, tableName, null);

        //load all of the metadata in the result set into a map for each column

        ResultSetMetaData rsmd = rs.getMetaData();
        int metaDataColumnCount = rsmd.getColumnCount();
        if (!rs.isBeforeFirst()) {
            throw new RuntimeException(
                    "No results for DatabaseMetaData.getColumns(" + verifiedSchema + "." + tableName + ")");
        }
        while (rs.next()) {
            ColumnDef columnDef = new ColumnDef();
            Map columnMetaData = new CaseInsensitiveMap();
            for (int i = 1; i <= metaDataColumnCount; i++) {
                columnMetaData.put(rsmd.getColumnName(i), rs.getString(i));
            }
            columnDef.setName(rs.getString("COLUMN_NAME"));

            String type_name = rs.getString("TYPE_NAME");
            if (type_name.equalsIgnoreCase("serial")) {
                columnDef.setTypeName("int4");
            } else {
                columnDef.setTypeName(type_name);
            }
            columnDef.setSqlType(rs.getInt("DATA_TYPE"));
            columnDef.setSize(rs.getInt("COLUMN_SIZE"));
            columnDef.setDecimalSize(rs.getInt("DECIMAL_DIGITS"));
            columnDef.setSourceMeta(columnMetaData);

            if (dtds.containsKey(columnDef.getTypeName())) {
                columnDef.setDataTypeDef(dtds.get(columnDef.getTypeName()));
            } else {
                throw new RuntimeException(
                        "Missing DATA_TYPE definition for data type " + columnDef.getTypeName());
            }
            columns.add(columnDef);
        }

    } catch (SQLException e) {
        throw Throwables.propagate(e);
    }

    return columns;

}

From source file:com.github.heartsemma.enderauth.Database.java

/**@param uuid (Universally Unique Identifier)
 * @return A boolean//from  ww w .  ja  v  a 2  s . c om
 * 
 * <br><Br>Returns true if there is an entry in the User Table with a uuid matching the parameter. 
 * <br>Returns false if there is not.
 * 
 * @throws SQLException The function uses PreparedStatements to ask about the presence of the UUID in the User Table.
 * @throws DatabaseException If the returned ResultSet from the SELECT command is completely empty (that is, lacking even the names of the columns in the table), the function throws a DatabaseException.*/
public boolean isInDatabase(byte[] uuid) throws SQLException, DatabaseException {
    logger.debug("Attempting to determine presence of user " + new String(uuid) + " in the database.");

    String isInDatabaseCommand = "SELECT * FROM ? WHERE ? = ?";

    ArrayList<Object> isInDatabaseVariables = new ArrayList<Object>();

    isInDatabaseVariables.add(1, userTableName);
    isInDatabaseVariables.add(2, userTableIDColumn);
    isInDatabaseVariables.add(3, uuid);

    //Command should look something like: SELECT * FROM ea_users WHERE id == uuid

    ResultSet selection = transact(isInDatabaseCommand, isInDatabaseVariables);

    logger.debug("Database inquiry returned the ResultSet: " + selection.toString() + ".");

    logger.debug("Error Checking...");
    Preconditions.checkNotNull(selection);

    //ResultSet Analysis + Error Checking
    if (selection.isBeforeFirst()) { //Triggers when there are no rows in the ResultSet.
        logger.error("EnderAuth attempted to find if there was a uuid matching " + new String(uuid)
                + " in the database but was unable to run the necessary SQL queries.");
        logger.error(
                "There were no rows in the returned table of data after running the MySql 'PreparedStatement'.");
        throw new DatabaseException("Returned ResultSet in isPresent(String uuid) contained no rows.");
    }

    selection.last();

    if (selection.getRow() == 1) { //There are no entries in the ResultSet.
        logger.debug("No entries for user " + new String(uuid) + " were found in the ResultSet.");
        return false;

    } else { //There is one or more entries with the matching uuid.
        logger.debug("User " + new String(uuid) + " was found in the database.");
        return true;
    }

}

From source file:synergyj.ListController.java

private boolean existsInDatabase(ToDoItem item) {

    try {//from w  w  w.  j a v  a2s.c  o m
        int listId = getEnsuredIdForListName(item.getListName());

        conn = getDbConnection();

        String stmt = "SELECT * FROM todoitems " + "WHERE ToDoItemText = ? " + "AND ListId = ? ";
        pSt = conn.prepareStatement(stmt);

        pSt.setString(1, item.getText());
        pSt.setInt(2, listId);
        ResultSet rs = pSt.executeQuery();

        //per javadoc, returns false if no rows
        if (rs.isBeforeFirst()) {
            Logger.log("ToDoItemText={" + item.getText() + "} ListName={" + item.getListName()
                    + "} found in database.");
        } else {
            Logger.log("ToDoItemText={" + item.getText() + "} ListName={" + item.getListName()
                    + "} not found in database.");
            return false;
        }
    } catch (ClassNotFoundException | SQLException ex) {
        Logger.log(ex.getMessage());
    } finally {
        try {
            if (pSt != null) {
                pSt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException ex) {
            Logger.log(ex.getMessage());
        }
    }

    return true;
}

From source file:it.unibas.spicy.persistence.json.ExportJsonInstances.java

public void createJsonDocument(String tableName, String schema, INode tableNode, String folderPath,
        Statement statement) throws SQLException, IOException {
    BufferedWriter bw = null;/*ww w .ja  v  a2s .  c o m*/
    ResultSet instancesSet = null;
    try {
        File file = new File(folderPath + File.separator + tableName + ".json");
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        bw = new BufferedWriter(fw);
        if (!file.exists()) {
            file.createNewFile();
        }
        instancesSet = statement.executeQuery(
                "SELECT row_to_json(\"" + tableName + "\") FROM " + schema + ".\"" + tableName + "\";");
        //check to see if the result set is empty
        if (instancesSet.isBeforeFirst()) {
            bw.write("[");
            bw.newLine();
            while (instancesSet.next()) {
                bw.write(instancesSet.getString(1));
                //if it is not the last result
                if (!instancesSet.isLast()) {
                    bw.write(",");
                }
                bw.newLine();
            }
            bw.write("]");
        }
        //alternative for one-row json 
        /*instancesSet = statement.executeQuery("SELECT array_to_json(array_agg("+"\""+tableName+"\")) FROM "+schema+"\""+tableName+"\";");
        while (instancesSet.next() && instancesSet.getString(1)!=null){ 
            bw.write(instancesSet.getString(1));
        }
        }*/
    } finally {
        bw.close();
        instancesSet.close();
    }
}

From source file:uk.ac.cam.cl.dtg.segue.dao.users.PgUsers.java

@Override
public RegisteredUser getByLinkedAccount(final AuthenticationProvider provider, final String providerUserId)
        throws SegueDatabaseException {
    try (Connection conn = database.getDatabaseConnection()) {
        PreparedStatement pst;//from   w  ww . j  ava 2  s .  co m
        pst = conn
                .prepareStatement("Select * FROM linked_accounts WHERE provider = ? AND provider_user_id = ?");
        pst.setString(1, provider.name());
        pst.setString(2, providerUserId);

        ResultSet results = pst.executeQuery();

        if (!results.isBeforeFirst()) {
            return null;
        } else {
            results.next();
        }

        return getById(results.getLong("user_id"));
    } catch (SQLException e) {
        throw new SegueDatabaseException("Postgres exception", e);
    }
}

From source file:uk.ac.cam.cl.dtg.segue.dao.users.PgUsers.java

@Override
public RegisteredUser getByLegacyId(final String id) throws SegueDatabaseException {
    // if the id is null then we won't find anyone so just return null.
    if (null == id) {
        return null;
    }//from w w w  . jav  a  2  s. co m

    // TODO Currently this uses the old mongo id for look ups.
    try (Connection conn = database.getDatabaseConnection()) {
        PreparedStatement pst;
        pst = conn.prepareStatement("SELECT * FROM users WHERE " + MASTER_ID + " = ?");
        pst.setString(1, id);

        ResultSet results = pst.executeQuery();

        if (!results.isBeforeFirst()) {
            return null;
        }

        return this.findOneUser(results);
    } catch (SQLException e) {
        throw new SegueDatabaseException("Postgres exception", e);
    }
}