Example usage for java.sql ResultSet wasNull

List of usage examples for java.sql ResultSet wasNull

Introduction

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

Prototype

boolean wasNull() throws SQLException;

Source Link

Document

Reports whether the last column read had a value of SQL NULL.

Usage

From source file:com.flexive.ejb.beans.HistoryTrackerEngineBean.java

/**
 * {@inheritDoc}/* ww w. j a v a  2  s .com*/
 */
@Override
public List<FxHistory> getEntries(String keyMatch, Long accountMatch, Long typeMatch, Long contentMatch,
        Date startDate, Date endDate, int maxEntries) {
    List<FxHistory> ret = new ArrayList<FxHistory>(100);
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        String query = "";
        if (accountMatch != null)
            query += " AND ACCOUNT=" + accountMatch;
        if (typeMatch != null)
            query += " AND TYPEID=" + typeMatch;
        if (contentMatch != null)
            query += " AND PKID=" + contentMatch;
        ps = con.prepareStatement(StorageManager.escapeReservedWords(HISTORY_SELECT)
                + " WHERE TIMESTP>=? AND TIMESTP<=? AND ACTION_KEY LIKE ? " + query + " ORDER BY TIMESTP DESC");
        ps.setLong(1, startDate == null ? 0 : startDate.getTime());
        ps.setLong(2, endDate == null ? Long.MAX_VALUE - 1 : endDate.getTime());
        ps.setString(3, (StringUtils.isEmpty(keyMatch) ? "" : keyMatch) + "%");
        ResultSet rs = ps.executeQuery();
        boolean loadData = FxContext.getUserTicket().isGlobalSupervisor();
        int count = 0;
        while (rs != null && rs.next()) {
            if (count++ >= maxEntries)
                break;
            long typeId = rs.getLong(8);
            if (rs.wasNull())
                typeId = -1;
            ret.add(new FxHistory(rs.getLong(3), rs.getLong(1), rs.getString(2), rs.getString(4),
                    rs.getString(5).split("\\|"), typeId, rs.getLong(9), rs.getInt(10), rs.getString(6),
                    rs.getString(7), loadData ? rs.getString(11) : "No permission to load to data!",
                    rs.getString(12)));
        }
    } catch (Exception ex) {
        LOG.error(ex.getMessage());
    } finally {
        Database.closeObjects(HistoryTrackerEngineBean.class, con, ps);
    }
    return ret;
}

From source file:com.nabla.wapp.server.json.SqlColumn.java

public void write(final ResultSet rs, int column, final JSONObject record) throws SQLException {
    switch (type) {
    case Types.BIGINT:
    case Types.INTEGER:
    case Types.SMALLINT:
    case Types.TINYINT:
        record.put(label, rs.getInt(column));
        break;//from  ww  w  . ja va2s  .  co m
    case Types.BOOLEAN:
    case Types.BIT:
        record.put(label, rs.getBoolean(column));
        break;
    case Types.DATE:
        final Date dt = rs.getDate(column);
        if (rs.wasNull())
            record.put(label, null);
        else
            record.put(label, new JSonDate(dt));
        return;
    case Types.TIMESTAMP:
        final Timestamp tm = rs.getTimestamp(column);
        if (rs.wasNull())
            record.put(label, null);
        else
            record.put(label, timeStampFormat.format(tm));
        return;
    case Types.DOUBLE:
        record.put(label, rs.getDouble(column));
        break;
    case Types.FLOAT:
        record.put(label, rs.getFloat(column));
        break;
    case Types.NULL:
        record.put(label, null);
        return;
    default:
        record.put(label, rs.getString(column));
        break;
    }
    if (rs.wasNull())
        record.put(label, null);
}

From source file:com.flexive.core.storage.genericSQL.GenericLockStorage.java

/**
 * {@inheritDoc}/*from  w  w  w.  j ava 2s  . co m*/
 */
@Override
@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
public List<FxLock> getUserLocks(Connection con, long userId) {
    List<FxLock> result = new ArrayList<FxLock>(10);
    PreparedStatement ps = null;
    try {
        //                                1        2          3          4       5        6
        ps = con.prepareStatement("SELECT LOCKTYPE,CREATED_AT,EXPIRES_AT,LOCK_ID,LOCK_VER,LOCK_RESOURCE FROM "
                + TBL_LOCKS + " WHERE USER_ID=?");
        ps.setLong(1, userId);
        ResultSet rs = ps.executeQuery();
        while (rs != null && rs.next()) {
            Object res = rs.getString(6);
            if (rs.wasNull())
                res = new FxPK(rs.getLong(4), rs.getInt(5));
            try {
                result.add(new FxLock(FxLockType.getById(rs.getInt(1)), rs.getLong(2), rs.getLong(3), userId,
                        res));
            } catch (FxLockException e) {
                LOG.warn(e);
            }
        }
    } catch (SQLException e) {
        throw new FxDbException(e, "ex.db.sqlError", e.getMessage()).asRuntimeException();
    } finally {
        Database.closeObjects(GenericLockStorage.class, null, ps);
    }
    return result;
}

From source file:com.flexive.core.storage.genericSQL.GenericLockStorage.java

/**
 * {@inheritDoc}/* w w w.jav a 2s. c o  m*/
 */
@Override
@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
public List<FxLock> getLocks(Connection con, FxLockType lockType, long userId, long typeId, String resource) {
    final UserTicket ticket = FxContext.getUserTicket();
    if (!(ticket.isGlobalSupervisor() || ticket.isMandatorSupervisor()))
        userId = ticket.getUserId();

    StringBuilder sql = new StringBuilder(500);
    sql.append(
            "SELECT l.LOCKTYPE,l.CREATED_AT,l.EXPIRES_AT,l.LOCK_ID,l.LOCK_VER,l.LOCK_RESOURCE,l.USER_ID FROM ")
            .append(TBL_LOCKS).append(" l");
    boolean hasWhere = false;
    if (typeId >= 0) {
        hasWhere = true;
        sql.append(", ").append(DatabaseConst.TBL_CONTENT).append(" c");
        sql.append(" WHERE c.ID=l.LOCK_ID AND c.VER=l.LOCK_VER AND c.TDEF=").append(typeId);
    }
    if (lockType != null) {
        if (!hasWhere) {
            hasWhere = true;
            sql.append(" WHERE ");
        } else
            sql.append(" AND ");
        sql.append("l.LOCKTYPE=").append(lockType.getId());
    }
    if (userId >= 0) {
        if (!hasWhere) {
            hasWhere = true;
            sql.append(" WHERE ");
        } else
            sql.append(" AND ");
        sql.append("l.USER_ID=").append(userId);
    }
    if (!StringUtils.isEmpty(resource)) {
        if (!hasWhere) {
            sql.append(" WHERE ");
        } else
            sql.append(" AND ");
        resource = resource.trim();
        //prevent sql injection, although only callable by global supervisors
        resource = resource.replace('\'', '_');
        resource = resource.replace('\"', '_');
        resource = resource.replace('%', '_');
        sql.append("l.LOCK_RESOURCE LIKE '%").append(resource).append("%'");
    }
    List<FxLock> result = new ArrayList<FxLock>(50);
    PreparedStatement ps = null;
    try {
        ps = con.prepareStatement(sql.toString());
        ResultSet rs = ps.executeQuery();
        while (rs != null && rs.next()) {
            Object res = rs.getString(6);
            if (rs.wasNull())
                res = new FxPK(rs.getLong(4), rs.getInt(5));
            try {
                result.add(new FxLock(FxLockType.getById(rs.getInt(1)), rs.getLong(2), rs.getLong(3),
                        rs.getLong(7), res));
            } catch (FxLockException e) {
                LOG.warn(e);
            }
        }
    } catch (SQLException e) {
        throw new FxDbException(e, "ex.db.sqlError", e.getMessage()).asRuntimeException();
    } finally {
        Database.closeObjects(GenericLockStorage.class, null, ps);
    }
    return result;
}

From source file:dk.netarkivet.harvester.datamodel.ScheduleDBDAO.java

/**
 * Read an existing schedule.//w  w w. ja v  a2 s  .com
 *
 * @param scheduleName the name of the schedule
 * @return The schedule read
 * @throws ArgumentNotValid if schedulename is null or empty
 * @throws UnknownID        if the schedule doesn't exist
 */
public synchronized Schedule read(String scheduleName) {
    ArgumentNotValid.checkNotNullOrEmpty(scheduleName, "String scheduleName");
    Connection c = HarvestDBConnection.get();
    PreparedStatement s = null;
    try {
        s = c.prepareStatement("SELECT schedule_id, comments, startdate, " + "enddate, maxrepeats, timeunit, "
                + "numtimeunits, anytime, onminute, " + "onhour, ondayofweek, ondayofmonth, edition "
                + "FROM schedules WHERE name = ?");
        s.setString(1, scheduleName);
        ResultSet rs = s.executeQuery();
        if (!rs.next()) {
            throw new UnknownID("No schedule named '" + scheduleName + "' found");
        }
        long id = rs.getLong(1);
        boolean isTimedSchedule;
        String comments = rs.getString(2);
        Date startdate = DBUtils.getDateMaybeNull(rs, 3);
        Date enddate = DBUtils.getDateMaybeNull(rs, 4);
        int maxrepeats = rs.getInt(5);
        isTimedSchedule = rs.wasNull();
        int timeunit = rs.getInt(6);
        int numtimeunits = rs.getInt(7);
        boolean anytime = rs.getBoolean(8);
        Integer minute = DBUtils.getIntegerMaybeNull(rs, 9);
        Integer hour = DBUtils.getIntegerMaybeNull(rs, 10);
        Integer dayofweek = DBUtils.getIntegerMaybeNull(rs, 11);
        Integer dayofmonth = DBUtils.getIntegerMaybeNull(rs, 12);
        log.debug("Creating frequency for " + "(timeunit,anytime,numtimeunits,hour, minute, dayofweek,"
                + "dayofmonth) = (" + timeunit + ", " + anytime + "," + numtimeunits + "," + minute + "," + hour
                + "," + dayofweek + "," + dayofmonth + "," + ")");
        Frequency freq = Frequency.getNewInstance(timeunit, anytime, numtimeunits, minute, hour, dayofweek,
                dayofmonth);
        long edition = rs.getLong(13);
        final Schedule schedule;
        if (isTimedSchedule) {
            schedule = Schedule.getInstance(startdate, enddate, freq, scheduleName, comments);
        } else {
            schedule = Schedule.getInstance(startdate, maxrepeats, freq, scheduleName, comments);
        }
        schedule.setID(id);
        schedule.setEdition(edition);
        return schedule;
    } catch (SQLException e) {
        throw new IOFailure(
                "SQL error reading schedule " + scheduleName + "\n" + ExceptionUtils.getSQLExceptionCause(e),
                e);
    } finally {
        DBUtils.closeStatementIfOpen(s);
        HarvestDBConnection.release(c);
    }
}

From source file:com.googlecode.psiprobe.controllers.sql.ExecuteSqlController.java

protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String resourceName = ServletRequestUtils.getStringParameter(request, "resource");
    String sql = ServletRequestUtils.getStringParameter(request, "sql", null);

    if (sql == null || sql.equals("") || sql.trim().equals("")) {
        request.setAttribute("errorMessage",
                getMessageSourceAccessor().getMessage("probe.src.dataSourceTest.sql.required"));

        return new ModelAndView(getViewName());
    }/*from   w w w  . ja va 2s . c  o  m*/

    int maxRows = ServletRequestUtils.getIntParameter(request, "maxRows", 0);
    int rowsPerPage = ServletRequestUtils.getIntParameter(request, "rowsPerPage", 0);
    int historySize = ServletRequestUtils.getIntParameter(request, "historySize", 0);

    // store current option values and query history in a session attribute

    HttpSession sess = request.getSession();
    DataSourceTestInfo sessData = (DataSourceTestInfo) sess.getAttribute(DataSourceTestInfo.DS_TEST_SESS_ATTR);

    synchronized (sess) {
        if (sessData == null) {
            sessData = new DataSourceTestInfo();
            sess.setAttribute(DataSourceTestInfo.DS_TEST_SESS_ATTR, sessData);
        }

        sessData.setMaxRows(maxRows);
        sessData.setRowsPerPage(rowsPerPage);
        sessData.setHistorySize(historySize);
        sessData.addQueryToHistory(sql);
    }

    DataSource dataSource = null;

    try {
        dataSource = getContainerWrapper().getResourceResolver().lookupDataSource(context, resourceName,
                getContainerWrapper());
    } catch (NamingException e) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    }

    if (dataSource == null) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    } else {
        List results = null;
        int rowsAffected = 0;

        try {
            // TODO: use Spring's jdbc template?
            Connection conn = dataSource.getConnection();

            try {
                conn.setAutoCommit(true);
                PreparedStatement stmt = conn.prepareStatement(sql);

                try {
                    boolean hasResultSet = stmt.execute();

                    if (!hasResultSet) {
                        rowsAffected = stmt.getUpdateCount();
                    } else {
                        results = new ArrayList();
                        ResultSet rs = stmt.getResultSet();

                        try {
                            ResultSetMetaData metaData = rs.getMetaData();

                            while (rs.next() && (maxRows < 0 || results.size() < maxRows)) {
                                Map record = new LinkedHashMap();

                                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                                    String value = rs.getString(i);

                                    if (rs.wasNull()) {
                                        value = getMessageSourceAccessor()
                                                .getMessage("probe.src.dataSourceTest.sql.null");
                                    } else {
                                        value = HtmlUtils.htmlEscape(value);
                                    }

                                    // a work around for IE browsers bug of not displaying
                                    // a border around an empty table column

                                    if (value.equals("")) {
                                        value = "&nbsp;";
                                    }

                                    // Pad the keys of columns with existing labels so they are distinct
                                    String key = metaData.getColumnLabel(i);
                                    while (record.containsKey(key)) {
                                        key += " ";
                                    }
                                    record.put(HtmlUtils.htmlEscape(key), value);
                                }

                                results.add(record);
                            }
                        } finally {
                            rs.close();
                        }

                        rowsAffected = results.size();
                    }
                } finally {
                    stmt.close();
                }
            } finally {
                conn.close();
            }

            // store the query results in the session attribute in order
            // to support a result set pagination feature without re-executing the query

            synchronized (sess) {
                sessData.setResults(results);
            }

            ModelAndView mv = new ModelAndView(getViewName(), "results", results);
            mv.addObject("rowsAffected", String.valueOf(rowsAffected));
            mv.addObject("rowsPerPage", String.valueOf(rowsPerPage));

            return mv;
        } catch (SQLException e) {
            String message = getMessageSourceAccessor().getMessage("probe.src.dataSourceTest.sql.failure",
                    new Object[] { e.getMessage() });
            logger.error(message, e);
            request.setAttribute("errorMessage", message);
        }
    }

    return new ModelAndView(getViewName());
}

From source file:com.act.lcms.db.model.ChemicalAssociatedWithPathway.java

@Override
protected List<ChemicalAssociatedWithPathway> fromResultSet(ResultSet resultSet) throws SQLException {
    List<ChemicalAssociatedWithPathway> results = new ArrayList<>();
    while (resultSet.next()) {
        Integer id = resultSet.getInt(DB_FIELD.INDEX.getOffset());
        String constructId = resultSet.getString(DB_FIELD.CONSTRUCT_ID.getOffset());
        String chemical = resultSet.getString(DB_FIELD.CHEMICAL.getOffset());
        String kind = resultSet.getString(DB_FIELD.KIND.getOffset());
        Integer index = resultSet.getInt(DB_FIELD.INDEX.getOffset());
        if (resultSet.wasNull()) {
            index = null;/*from ww w .j av  a2  s. co m*/
        }
        results.add(new ChemicalAssociatedWithPathway(id, constructId, chemical, kind, index));
    }

    return results;

}

From source file:com.splicemachine.derby.impl.load.HdfsUnsafeImportIT.java

/**
 * Worker method for import tests related to CSV files that are missing the end quote for a quoted column.
 *
 * @param schemaName     table schema/*from  www.ja va 2  s.c  o m*/
 * @param tableName      table name
 * @param importFilePath full path to the import file
 * @param colList        list of columns and their order
 * @param badDir         where to place the error file
 * @param failErrorCount how many errors do we allow before failing the whole import
 * @param importCount    verification of number of rows imported
 * @param oneLineRecords whether the import file has one record per line or records span lines
 * @throws Exception
 */
private void testMissingEndQuoteForQuotedColumn(String schemaName, String tableName, String importFilePath,
        String colList, String badDir, int failErrorCount, int importCount, String oneLineRecords)
        throws Exception {
    methodWatcher.executeUpdate("delete from " + schemaName + "." + tableName);
    PreparedStatement ps = methodWatcher.prepareStatement(format(
            "call SYSCS_UTIL.IMPORT_DATA_UNSAFE('%s','%s','%s','%s',',',null,null,null,null,%d,'%s','%s',null)",
            schemaName, tableName, colList, importFilePath, failErrorCount, badDir, oneLineRecords));
    ps.execute();
    ResultSet rs = methodWatcher.executeQuery(format("select * from %s.%s", schemaName, tableName));
    List<String> results = Lists.newArrayList();
    while (rs.next()) {
        String name = rs.getString(1);
        String title = rs.getString(2);
        int age = rs.getInt(3);
        Assert.assertTrue("age was null!", !rs.wasNull());
        assertNotNull("name is null!", name);
        assertNotNull("title is null!", title);
        results.add(String.format("name:%s,title:%s,age:%d", name, title, age));
    }
    Assert.assertEquals("Incorrect number of rows imported", importCount, results.size());
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_0.CFAstPgSql.CFAstPgSqlSchema.java

public static Integer getNullableInt32(ResultSet reader, int colidx) {
    try {//from ww w. j  a  v  a2 s. c  om
        int val = reader.getInt(colidx);
        if (reader.wasNull()) {
            return (null);
        } else {
            return (new Integer(val));
        }
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(CFAstPgSqlSchema.class, "getNullableInt32", e);
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_0.CFAstPgSql.CFAstPgSqlSchema.java

public static Integer getNullableUInt16(ResultSet reader, int colidx) {
    try {/*from   ww w  . j  a v a  2s. c om*/
        int val = reader.getInt(colidx);
        if (reader.wasNull()) {
            return (null);
        } else {
            return (new Integer(val));
        }
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(CFAstPgSqlSchema.class, "getNullableUInt16", e);
    }
}