Example usage for java.sql PreparedStatement setNull

List of usage examples for java.sql PreparedStatement setNull

Introduction

In this page you can find the example usage for java.sql PreparedStatement setNull.

Prototype

void setNull(int parameterIndex, int sqlType) throws SQLException;

Source Link

Document

Sets the designated parameter to SQL NULL.

Usage

From source file:ar.com.zauber.commons.repository.utils.URIUserType.java

/**
 * @see UserType#nullSafeSet(PreparedStatement, Object, int)
 * @throws HibernateException//  w w w. j  a  v a  2 s  . c  om
 *             on error
 * @throws SQLException
 *             on error
 */
public final void nullSafeSet(final PreparedStatement st, final Object value, final int index)
        throws HibernateException, SQLException {
    Validate.notNull(st);
    Validate.isTrue(value == null || value instanceof URI);
    if (value == null) {
        st.setNull(index, Types.VARCHAR);
    } else {
        st.setString(index, ((URI) value).toString());
    }

}

From source file:jp.co.tis.gsp.tools.dba.dialect.SqlserverDialect.java

@Override
public void setObjectInStmt(PreparedStatement stmt, int parameterIndex, String value, int sqlType)
        throws SQLException {
    if (sqlType == UN_USABLE_TYPE) {
        stmt.setNull(parameterIndex, Types.NULL);
    } else if (StringUtil.isBlank(value) || "".equals(value)) {
        stmt.setNull(parameterIndex, sqlType);
    } else if (sqlType == Types.TIME) {
        stmt.setTimestamp(parameterIndex, Timestamp.valueOf("1970-01-01 " + value));
    } else {//from   w ww .  j  a v a  2 s.  c  o  m
        stmt.setObject(parameterIndex, value, sqlType);
    }
}

From source file:com.aw.core.dao.AWQueryExecuter.java

private <Rsl> List<Rsl> executeSQL(RowHandler<Rsl> rowHandler) {
    try {// ww  w  .  j a va2  s . c  om
        PreparedStatement stmt = connection.prepareStatement(sql);
        if (sqlParams != null)
            for (int i = 0; i < sqlParams.length; i++) {
                Object sqlParam = sqlParams[i];
                if (sqlParam == null)
                    stmt.setNull(i + 1, Types.VARCHAR);
                else
                    stmt.setObject(i + 1, sqlParam);

            }
        List<Rsl> results = new ArrayList<Rsl>(AWQueryAbortable.DEF_LIST_SIZE);
        if (logger.isDebugEnabled())
            logger.debug(DAOSql.buildSQL(sql, sqlParams));
        ResultSet rs = stmt.executeQuery();
        AWQueryAbortable queryAbortable = AWQueryAbortable.instance();
        queryAbortable.resetRowCount();
        while (rs.next()) {
            if (queryAbortable.isAborted())
                break;
            Rsl rsl = rowHandler.handle(rs);
            results.add(rsl);
            queryAbortable.incRowCount();
        }
        logger.debug("Results :" + results.size() + " abortedQuery:" + queryAbortable.isAborted());
        rs.close();
        stmt.close();
        return results;
    } catch (Exception e) {
        logger.error("SQL:" + sql);
        throw AWBusinessException.wrapUnhandledException(logger, e);
    }
}

From source file:jp.co.tis.gsp.tools.dba.dialect.MysqlDialect.java

@Override
public void setObjectInStmt(PreparedStatement stmt, int parameterIndex, String value, int sqlType)
        throws SQLException {
    if (sqlType == UN_USABLE_TYPE) {
        stmt.setNull(parameterIndex, Types.NULL);
    } else if (StringUtil.isBlank(value) || "".equals(value)) {
        stmt.setNull(parameterIndex, sqlType);
    } else if (sqlType == Types.TIMESTAMP) {
        stmt.setTimestamp(parameterIndex, Timestamp.valueOf(value));
    } else {// w ww .j ava2s .co  m
        stmt.setObject(parameterIndex, value, sqlType);
    }
}

From source file:at.bestsolution.persistence.java.Util.java

public static void setValue(PreparedStatement pstmt, int parameterIndex, TypedValue value) throws SQLException {
    if (value.value == null) {
        int sqlType;
        switch (value.type) {
        case INT:
            sqlType = Types.INTEGER;
            break;
        case DOUBLE:
            sqlType = Types.DECIMAL;
            break;
        case FLOAT:
            sqlType = Types.FLOAT;
            break;
        case BOOLEAN:
            sqlType = Types.BOOLEAN;
            break;
        case LONG:
            sqlType = Types.BIGINT;
            break;
        case STRING:
            sqlType = Types.VARCHAR;
            break;
        case BLOB:
            sqlType = Types.BLOB;
            break;
        case CLOB:
            sqlType = Types.CLOB;
            break;
        case TIMESTAMP:
            sqlType = Types.TIMESTAMP;
            break;
        default://ww  w.ja  v  a2  s.  c  o  m
            sqlType = Types.OTHER;
            break;
        }
        pstmt.setNull(parameterIndex, sqlType);
    } else {
        switch (value.type) {
        case INT:
            pstmt.setInt(parameterIndex, ((Number) value.value).intValue());
            break;
        case DOUBLE:
            pstmt.setDouble(parameterIndex, ((Number) value.value).doubleValue());
            break;
        case FLOAT:
            pstmt.setDouble(parameterIndex, ((Number) value.value).doubleValue());
            break;
        case BOOLEAN:
            pstmt.setBoolean(parameterIndex, Boolean.TRUE.equals(value.value));
            break;
        case LONG:
            pstmt.setLong(parameterIndex, ((Number) value.value).longValue());
            break;
        case STRING:
            pstmt.setString(parameterIndex, (String) value.value);
            break;
        case TIMESTAMP:
            if (value.value instanceof Timestamp) {
                pstmt.setTimestamp(parameterIndex, (Timestamp) value.value);
            } else {
                pstmt.setTimestamp(parameterIndex, new Timestamp(((Date) value.value).getTime()));
            }
            break;
        case UNKNOWN:
            pstmt.setObject(parameterIndex, value.value);
            break;
        default:
            throw new IllegalStateException("Unknown type");
        }
    }
}

From source file:org.jivesoftware.openfire.auth.DefaultAuthProvider.java

public void setPassword(String username, String password) throws UserNotFoundException {
    // Determine if the password should be stored as plain text or encrypted.
    boolean usePlainPassword = JiveGlobals.getBooleanProperty("user.usePlainPassword");
    String encryptedPassword = null;
    if (username.contains("@")) {
        // Check that the specified domain matches the server's domain
        int index = username.indexOf("@");
        String domain = username.substring(index + 1);
        if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
            username = username.substring(0, index);
        } else {/*from   w  ww .j  ava 2  s .co m*/
            // Unknown domain.
            throw new UserNotFoundException();
        }
    }
    if (!usePlainPassword) {
        try {
            encryptedPassword = AuthFactory.encryptPassword(password);
            // Set password to null so that it's inserted that way.
            password = null;
        } catch (UnsupportedOperationException uoe) {
            // Encryption may fail. In that case, ignore the error and
            // the plain password will be stored.
        }
    }

    Connection con = null;
    PreparedStatement pstmt = null;
    try {
        con = DbConnectionManager.getConnection();
        pstmt = con.prepareStatement(UPDATE_PASSWORD);
        if (password == null) {
            pstmt.setNull(1, Types.VARCHAR);
        } else {
            pstmt.setString(1, password);
        }
        if (encryptedPassword == null) {
            pstmt.setNull(2, Types.VARCHAR);
        } else {
            pstmt.setString(2, encryptedPassword);
        }
        pstmt.setString(3, username);
        pstmt.executeUpdate();
    } catch (SQLException sqle) {
        throw new UserNotFoundException(sqle);
    } finally {
        DbConnectionManager.closeConnection(pstmt, con);
    }
}

From source file:de.whs.poodle.repositories.CourseRepository.java

public void create(Course course, String firstTermName) {
    try {/*from w w  w. j  ava  2s  . co  m*/
        int id = jdbc.query(con -> {
            // the function creates the course and the first term (firstTermId)
            PreparedStatement ps = con.prepareStatement("SELECT * FROM create_course(?,?,?,?,?,?,?)");
            ps.setInt(1, course.getInstructor().getId());
            ps.setString(2, course.getName());
            ps.setBoolean(3, course.getVisible());
            if (course.getPassword().trim().isEmpty())
                ps.setNull(4, Types.VARCHAR);
            else
                ps.setString(4, course.getPassword());

            Array otherInstructors = con.createArrayOf("int4", course.getOtherInstructorsIds().toArray());
            ps.setArray(5, otherInstructors);
            Array linkedCourses = con.createArrayOf("int4", course.getLinkedCoursesIds().toArray());
            ps.setArray(6, linkedCourses);
            ps.setString(7, firstTermName);
            return ps;
        }, new ResultSetExtractor<Integer>() {

            @Override
            public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {
                rs.next();
                return rs.getInt(1);
            }
        });

        course.setId(id);
    } catch (DuplicateKeyException e) {
        throw new BadRequestException();
    }
}

From source file:ru.org.linux.user.ProfileDao.java

public void writeProfile(@Nonnull final User user, @Nonnull final Profile profile) {
    String boxlets[] = null;/*www .  jav  a  2 s  . c o  m*/

    List<String> customBoxlets = profile.getCustomBoxlets();

    if (customBoxlets != null) {
        boxlets = customBoxlets.toArray(new String[customBoxlets.size()]);
    }

    final String[] finalBoxlets = boxlets;
    if (jdbcTemplate.update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement st = con
                    .prepareStatement("UPDATE user_settings SET settings=?, main=? WHERE id=?");

            st.setObject(1, profile.getSettings());

            if (finalBoxlets != null) {
                st.setArray(2, con.createArrayOf("text", finalBoxlets));
            } else {
                st.setNull(2, Types.ARRAY);
            }

            st.setInt(3, user.getId());

            return st;
        }
    }) == 0) {
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement st = con
                        .prepareStatement("INSERT INTO user_settings (id, settings, main) VALUES (?,?,?)");

                st.setInt(1, user.getId());

                st.setObject(2, profile.getSettings());

                if (finalBoxlets != null) {
                    st.setArray(3, con.createArrayOf("text", finalBoxlets));
                } else {
                    st.setNull(3, Types.ARRAY);
                }

                return st;
            }
        });
    }
}

From source file:org.efaps.db.wrapper.AbstractSQLInsertUpdate.java

/**
 * Defines a new column <code>_columnName</code> with {@link Double}
 * <code>_value</code> within this SQL insert / update statement.
 *
 * @param _columnName   name of the column
 * @param _value        value of the column
 * @return this SQL statement//from   w  ww  .  j ava  2s  .  co m
 */
@SuppressWarnings("unchecked")
public STMT column(final String _columnName, final Double _value) {
    this.columnWithValues.add(new AbstractSQLInsertUpdate.AbstractColumnWithValue<Double>(_columnName, _value) {
        @Override
        public void set(final int _index, final PreparedStatement _stmt) throws SQLException {
            if (getValue() == null) {
                _stmt.setNull(_index, Types.DECIMAL);
            } else {
                _stmt.setDouble(_index, getValue());
            }
        }
    });
    return (STMT) this;
}

From source file:org.efaps.db.wrapper.AbstractSQLInsertUpdate.java

/**
 * Defines a new column <code>_columnName</code> with {@link String}
 * <code>_value</code> within this SQL insert / update statement.
 *
 * @param _columnName   name of the column
 * @param _value        value of the column
 * @return this SQL statement// w  ww.j  a v  a  2s.c  o m
 */
@SuppressWarnings("unchecked")
public STMT column(final String _columnName, final String _value) {
    this.columnWithValues.add(new AbstractSQLInsertUpdate.AbstractColumnWithValue<String>(_columnName, _value) {
        @Override
        public void set(final int _index, final PreparedStatement _stmt) throws SQLException {
            if (getValue() == null) {
                _stmt.setNull(_index, Types.VARCHAR);
            } else {
                _stmt.setString(_index, getValue());
            }
        }
    });
    return (STMT) this;
}