Example usage for java.sql PreparedStatement execute

List of usage examples for java.sql PreparedStatement execute

Introduction

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

Prototype

boolean execute() throws SQLException;

Source Link

Document

Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.

Usage

From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

private <T> boolean advanceDelete(Class<T> kind, Set<String> propertyNames,
        Map<String, WBLocalQueryOperator> operators, Map<String, Object> values)
        throws SQLException, WPBSerializerException {
    List<String> propertiesList = new ArrayList<String>();
    propertiesList.addAll(propertyNames);

    String condition = "";
    for (String property : propertiesList) {
        if (!hasClassProperty(kind, property)) {
            throw new SQLException("queryProperty value does not match a field of given Class kind");
        }//from   www  . j  a va  2s. co m
        if (condition.length() > 0) {
            condition = condition.concat("AND");
        }
        condition = condition.concat("(").concat(property).concat(operatorToString(operators.get(property)))
                .concat("?").concat(")");
    }
    String tableName = kind.getSimpleName();
    String queryString = String.format("DELETE FROM %s WHERE %s", tableName, condition);

    Connection connection = getConnection();
    PreparedStatement preparedStatement = null;
    try {
        preparedStatement = connection.prepareStatement(queryString);

        for (int i = 0; i < propertiesList.size(); i++) {
            setPrepareStatementParameter(preparedStatement, i + 1, values.get(propertiesList.get(i)));
        }
        return preparedStatement.execute();

    } catch (SQLException e) {
        throw e;
    } finally {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:de.iritgo.aktario.jdbc.JDBCManager.java

/**
 * Delete a data object from the database.
 *
 * @param object The data object to create.
 * @param owner The data object owning this one.
 * @param listAttribute The name of the list attribute to which the new
 *   object belongs./*  w ww .ja  va 2 s  .  co  m*/
 */
private void delete(DataObject object, DataObject owner, String listAttribute) {
    Connection connection = null;
    PreparedStatement stmt = null;

    try {
        connection = defaultDataSource.getConnection();

        StringBuffer sqlFields = new StringBuffer("id");
        StringBuffer sqlValues = new StringBuffer("?");

        String sql = "delete from IritgoObjectList where type='" + owner.getTypeId() + "'" + " AND id="
                + owner.getUniqueId() + " AND attribute='" + listAttribute + "'" + " AND elemType='"
                + object.getTypeId() + "'" + " AND elemId=" + object.getUniqueId();

        stmt = connection.prepareStatement(sql);
        stmt.execute();
        DbUtils.closeQuietly(stmt);

        sql = "delete from " + object.getTypeId() + " where id=" + object.getUniqueId();

        stmt = connection.prepareStatement(sql);
        stmt.execute();

        Log.logVerbose("persist", "JDBCManager",
                "Removed " + object.getTypeId() + ":" + object.getUniqueId() + " |" + sql + "|");

    } catch (Exception x) {
        //          Log.logError ("persist", "JDBCManager", "Error while removed a database record: " + x);
    } finally {
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:mysql5.MySQL5PlayerDAO.java

/**
 * {@inheritDoc} - KID//from   w w  w .ja  v  a 2 s .  co  m
 */
@Override
public void setPlayerLastTransferTime(final int playerId, final long time) {
    DB.insertUpdate("UPDATE players SET last_transfer_time=? WHERE id=?", new IUStH() {
        @Override
        public void handleInsertUpdate(PreparedStatement stmt) throws SQLException {
            stmt.setLong(1, time);
            stmt.setInt(2, playerId);
            stmt.execute();
        }
    });
}

From source file:com.concursive.connect.web.modules.documents.dao.FileFolder.java

/**
 * Deletes the folder and any enclosed files
 *
 * @param db Description of the Parameter
 * @return Description of the Return Value
 * @throws SQLException Description of the Exception
 *//*from ww  w .ja  v  a2s.  c o m*/
public boolean delete(Connection db, String baseFilePath) throws SQLException {
    if (id == -1) {
        return false;
    }
    boolean result = false;
    boolean commit = db.getAutoCommit();
    try {
        if (commit) {
            db.setAutoCommit(false);
        }
        // Build a list of files to delete
        FileItemList fileItemList = new FileItemList();
        fileItemList.setFolderId(id);
        fileItemList.buildList(db);
        fileItemList.delete(db, baseFilePath);
        // Build a list of folders to delete
        FileFolderList folderList = new FileFolderList();
        folderList.setParentId(id);
        folderList.buildList(db);
        folderList.delete(db, baseFilePath);
        // Delete this folder
        PreparedStatement pst = db.prepareStatement("DELETE FROM project_folders " + "WHERE folder_id = ?");
        pst.setInt(1, id);
        pst.execute();
        pst.close();
        if (commit) {
            db.commit();
        }
        result = true;
    } catch (Exception e) {
        LOG.error("Could not delete folder", e);
        if (commit) {
            db.rollback();
        }
    } finally {
        if (commit) {
            db.setAutoCommit(true);
        }
    }
    return result;
}

From source file:com.threecrickets.prudence.cache.SqlCache.java

public void invalidate(String tag) {
    try {/*from  w ww  . ja v  a2s .co  m*/
        Connection connection = connect();
        if (connection == null)
            return;

        try {
            List<String> tagged = getTagged(connection, tag);
            if (tagged.isEmpty())
                return;

            ArrayList<Lock> locks = new ArrayList<Lock>(tagged.size());

            String sql = "DELETE FROM " + cacheTableName + " WHERE key IN (";
            for (String key : tagged) {
                sql += "?,";
                locks.add(lockSource.getWriteLock(key));
            }
            sql = sql.substring(0, sql.length() - 1) + ")";

            for (Lock lock : locks)
                lock.lock();
            try {
                PreparedStatement statement = connection.prepareStatement(sql);
                try {
                    int i = 1;
                    for (String key : tagged)
                        statement.setString(i++, key);
                    if (!statement.execute())
                        logger.fine("Invalidated " + statement.getUpdateCount());
                } finally {
                    statement.close();
                }

                for (String key : tagged)
                    lockSource.discard(key);
            } finally {
                for (Lock lock : locks)
                    lock.unlock();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException x) {
        logger.log(Level.WARNING, "Could not invalidate cache tag", x);
    }
}

From source file:com.base2.kagura.core.report.connectors.FreemarkerSQLDataReportConnector.java

/**
 * Runs freemarker against the 3 sql queries, then executes them in order.
 * {@inheritDoc}/*from   w ww .  j  ava 2s .co m*/
 */
@Override
public void runReport(Map<String, Object> extra) {
    PreparedStatement prestatement = null;
    PreparedStatement poststatement = null;
    PreparedStatement statement = null;
    try {
        getStartConnection();
        if (StringUtils.isNotBlank(presql)) {
            FreemarkerSQLResult prefreemarkerSQLResult = freemakerParams(extra, false, presql);
            prestatement = connection.prepareStatement(prefreemarkerSQLResult.getSql());
            for (int i = 0; i < prefreemarkerSQLResult.getParams().size(); i++) {
                prestatement.setObject(i + 1, prefreemarkerSQLResult.getParams().get(i));
            }
            prestatement.setQueryTimeout(queryTimeout);
            prestatement.execute();
        }
        FreemarkerSQLResult freemarkerSQLResult = freemakerParams(extra, true, freemarkerSql);
        statement = connection.prepareStatement(freemarkerSQLResult.getSql());
        for (int i = 0; i < freemarkerSQLResult.getParams().size(); i++) {
            statement.setObject(i + 1, freemarkerSQLResult.getParams().get(i));
        }
        statement.setQueryTimeout(queryTimeout);
        rows = resultSetToMap(statement.executeQuery());
        if (StringUtils.isNotBlank(postsql)) {
            FreemarkerSQLResult postfreemarkerSQLResult = freemakerParams(extra, false, postsql);
            poststatement = connection.prepareStatement(postfreemarkerSQLResult.getSql());
            for (int i = 0; i < postfreemarkerSQLResult.getParams().size(); i++) {
                poststatement.setObject(i + 1, postfreemarkerSQLResult.getParams().get(i));
            }
            poststatement.setQueryTimeout(queryTimeout);
            poststatement.execute();
        }
    } catch (Exception ex) {
        errors.add(ex.getMessage());
    } finally {
        try {
            if (statement != null && !statement.isClosed()) {
                statement.close();
                statement = null;
            }
            if (prestatement != null && !prestatement.isClosed()) {
                prestatement.close();
                prestatement = null;
            }
            if (poststatement != null && !poststatement.isClosed()) {
                poststatement.close();
                poststatement = null;
            }
            if (connection != null && !connection.isClosed()) {
                connection.close();
                connection = null;
            }
        } catch (SQLException e) {
            errors.add(e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:ke.co.tawi.babblesms.server.persistence.notification.NotificationDAO.java

/**
 * //from   ww  w .  j  a v a 2s . c o  m
 * @param notification
 * @return 
 */
@Override
public boolean updateNotification(Notification notification) {
    boolean success = true;

    Connection conn = null;
    PreparedStatement pstmt = null;

    try {
        conn = dbCredentials.getConnection();
        pstmt = conn.prepareStatement(
                "UPDATE Notification SET origin=?,ShortDesc=?,LongDesc=?,published=? WHERE uuid=?");

        pstmt.setString(1, notification.getOrigin());
        pstmt.setString(2, notification.getShortDesc());
        pstmt.setString(3, notification.getLongDesc());
        pstmt.setString(4, notification.getPublished());
        pstmt.setString(5, notification.getUuid());

        pstmt.execute();

    } catch (SQLException e) {
        logger.error("SQL Exception when trying to putupdate Notification: " + notification);
        logger.error(ExceptionUtils.getStackTrace(e));
        success = false;
    } finally {
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
    return success;
}

From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public void testInsertFunction() throws SQLException {
    Statement stat = conn.createStatement();
    PreparedStatement prep;
    ResultSet rs;//w  w w  . j av  a2 s . c  om

    stat.execute("CREATE TABLE TEST(ID INT, H BINARY)");
    prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, HASH('SHA256', STRINGTOUTF8(?), 5))");
    prep.setInt(1, 1);
    prep.setString(2, "One");
    prep.execute();
    prep.setInt(1, 2);
    prep.setString(2, "Two");
    prep.execute();
    rs = stat.executeQuery("SELECT COUNT(DISTINCT H) FROM TEST");
    rs.next();
    assertEquals(2, rs.getInt(1));

    stat.execute("DROP TABLE TEST");
}

From source file:com.webpagebytes.plugins.WPBSQLDataStoreDao.java

private <T> boolean advanceDelete(Class<T> kind, Set<String> propertyNames,
        Map<String, WBSQLQueryOperator> operators, Map<String, Object> values)
        throws SQLException, WPBSerializerException {
    List<String> propertiesList = new ArrayList<String>();
    propertiesList.addAll(propertyNames);

    String condition = "";
    for (String property : propertiesList) {
        if (!hasClassProperty(kind, property)) {
            throw new SQLException("queryProperty value does not match a field of given Class kind");
        }/*from   w  ww. j  a  va2s. c o  m*/
        if (condition.length() > 0) {
            condition = condition.concat("AND");
        }
        condition = condition.concat("(").concat(property).concat(operatorToString(operators.get(property)))
                .concat("?").concat(")");
    }
    String tableName = kind.getSimpleName();
    String queryString = String.format("DELETE FROM %s WHERE %s", tableName, condition);

    Connection connection = getConnection();
    PreparedStatement preparedStatement = null;
    try {
        preparedStatement = connection.prepareStatement(queryString);

        for (int i = 0; i < propertiesList.size(); i++) {
            setPrepareStatementParameter(preparedStatement, i + 1, values.get(propertiesList.get(i)));
        }
        return preparedStatement.execute();

    } catch (SQLException e) {
        throw e;
    } finally {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:net.sf.l2j.gameserver.handler.admincommandhandlers.AdminDonator.java

public boolean useAdminCommand(String command, L2PcInstance activeChar) {
    if (!Config.ALT_PRIVILEGES_ADMIN) {
        if (!(checkLevel(activeChar.getAccessLevel()) && activeChar.isGM())) {
            return false;
        }/*from w  w  w . jav a 2s .c  om*/
    }
    if (command.startsWith("admin_setdonator")) {
        L2Object target = activeChar.getTarget();
        L2PcInstance player = null;
        SystemMessage sm = new SystemMessage(SystemMessageId.S1_S2);
        if (target instanceof L2PcInstance) {
            player = (L2PcInstance) target;
        } else {
            player = activeChar;
        }
        if (player.isDonator()) {
            player.setDonator(false);
            sm.addString("You are no longer a server donator.");
            Connection connection = null;
            try {
                connection = L2DatabaseFactory.getInstance().getConnection();
                PreparedStatement statement = connection
                        .prepareStatement("SELECT obj_id FROM characters where char_name=?");
                statement.setString(1, target.getName());
                ResultSet rset = statement.executeQuery();
                int objId = 0;
                if (rset.next()) {
                    objId = rset.getInt(1);
                }
                rset.close();
                statement.close();
                if (objId == 0) {
                    connection.close();
                    return false;
                }
                statement = connection.prepareStatement("UPDATE characters SET donator=0 WHERE obj_id=?");
                statement.setInt(1, objId);
                statement.execute();
                statement.close();
                connection.close();
            } catch (Exception e) {
                _log.warn("could not set donator stats of char:", e);
            } finally {
                try {
                    connection.close();
                } catch (Exception e) {
                }
            }
        } else {
            player.setDonator(true);
            sm.addString("You are now a server donator, congratulations!");
            Connection connection = null;
            try {
                connection = L2DatabaseFactory.getInstance().getConnection();
                PreparedStatement statement = connection
                        .prepareStatement("SELECT obj_id FROM characters where char_name=?");
                statement.setString(1, target.getName());
                ResultSet rset = statement.executeQuery();
                int objId = 0;
                if (rset.next()) {
                    objId = rset.getInt(1);
                }
                rset.close();
                statement.close();
                if (objId == 0) {
                    connection.close();
                    return false;
                }
                statement = connection.prepareStatement("UPDATE characters SET donator=1 WHERE obj_id=?");
                statement.setInt(1, objId);
                statement.execute();
                statement.close();
                connection.close();
            } catch (Exception e) {
                _log.warn("could not set donator stats of char:", e);
            } finally {
                try {
                    connection.close();
                } catch (Exception e) {
                }
            }
        }
        player.sendPacket(sm);
        player.broadcastUserInfo();
        if (player.isDonator() == true) {
            Announcements.getInstance().announceToAll(player.getName() + " Has Become a Server Donator!");
        }
    }
    return false;
}