Example usage for java.sql PreparedStatement close

List of usage examples for java.sql PreparedStatement close

Introduction

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

Prototype

void close() throws SQLException;

Source Link

Document

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.

Usage

From source file:com.consol.citrus.samples.todolist.dao.JdbcTodoListDao.java

@Override
public void deleteByTitle(String title) {
    try {/*from  w  w  w . j  a  va  2  s .c  o  m*/
        Connection connection = getConnection();
        try {
            connection.setAutoCommit(true);
            PreparedStatement statement = connection
                    .prepareStatement("DELETE FROM todo_entries WHERE title = ?");
            try {
                statement.setString(1, title);
                statement.executeUpdate();
            } finally {
                statement.close();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException e) {
        throw new DataAccessException("Could not delete entries for title " + title, e);
    }
}

From source file:com.cloudera.sqoop.manager.MySQLCompatTest.java

@Override
protected void dropTableIfExists(String table) throws SQLException {
    Connection conn = getManager().getConnection();
    PreparedStatement statement = conn.prepareStatement("DROP TABLE IF EXISTS " + table,
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    try {/*www  . j a v  a  2s . c o  m*/
        statement.executeUpdate();
        conn.commit();
    } finally {
        statement.close();
    }
}

From source file:com.concursive.connect.web.modules.search.utils.SearchUtils.java

/**
 * Generates a list of projects that the user has access to
 *
 * @param db//  w w  w  .j  a va2  s.c  o  m
 * @param userId
 * @param specificProjectId
 * @param specificCategoryId
 * @return
 * @throws SQLException
 */
public static String generateValidProjects(Connection db, int userId, int specificProjectId,
        int specificCategoryId) throws SQLException {
    if (userId < 1) {
        return "";
    }
    // @todo get ids from user cache
    // @update cache everytime a user is added or removed from a project team
    // get the projects for the user
    // get the project permissions for each project
    // if user has access to the data, then add to query
    StringBuffer projectList = new StringBuffer();
    PreparedStatement pst = db
            .prepareStatement("SELECT project_id " + "FROM project_team " + "WHERE user_id = ? "
                    + "AND status IS NULL " + (specificProjectId > -1 ? "AND project_id = ? " : "")
                    + (specificCategoryId > -1
                            ? "AND project_id IN (SELECT project_id FROM projects WHERE category_id = ?) "
                            : ""));
    int i = 0;
    pst.setInt(++i, userId);
    if (specificProjectId > -1) {
        pst.setInt(++i, specificProjectId);
    }
    if (specificCategoryId > -1) {
        pst.setInt(++i, specificCategoryId);
    }
    ResultSet rs = pst.executeQuery();
    while (rs.next()) {
        int projectId = rs.getInt("project_id");
        // these projects override the lower access projects
        if (projectList.length() > 0) {
            projectList.append(" OR ");
        }
        projectList.append(projectId);
    }
    rs.close();
    pst.close();
    return projectList.toString();
}

From source file:at.becast.youploader.account.Account.java

public void updateCookie(int id) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    LOG.info("Updating account");
    try {//from   w w w. j av  a  2 s .  c  o m
        PreparedStatement stmt = c.prepareStatement("UPDATE `accounts` SET `cookie`=? WHERE `id`=?");
        stmt.setString(1, mapper.writeValueAsString(this.cdata));
        stmt.setInt(2, id);
        stmt.execute();
        stmt.close();
    } catch (SQLException e) {
        LOG.error("Could not update account Ex:", e);
    }
}

From source file:com.l2jfree.gameserver.instancemanager.ItemsOnGroundManager.java

private void load() {
    // If SaveDroppedItem is false, may want to delete all items previously stored to avoid add old items on reactivate
    if (!Config.SAVE_DROPPED_ITEM && Config.CLEAR_DROPPED_ITEM_TABLE)
        emptyTable();/*from ww w. j av a  2  s  . co  m*/

    if (!Config.SAVE_DROPPED_ITEM)
        return;

    // if DestroyPlayerDroppedItem was previously  false, items curently protected will be added to ItemsAutoDestroy
    if (Config.DESTROY_DROPPED_PLAYER_ITEM) {
        Connection con = null;
        try {
            String str = null;
            if (!Config.DESTROY_EQUIPABLE_PLAYER_ITEM) // Recycle misc. items only
                str = "UPDATE itemsonground SET drop_time=? WHERE drop_time=-1 AND equipable=0";
            else if (Config.DESTROY_EQUIPABLE_PLAYER_ITEM) // Recycle all items including equipable
                str = "UPDATE itemsonground SET drop_time=? WHERE drop_time=-1";
            con = L2DatabaseFactory.getInstance().getConnection(con);
            PreparedStatement statement = con.prepareStatement(str);
            statement.setLong(1, System.currentTimeMillis());
            statement.execute();
            statement.close();
        } catch (Exception e) {
            _log.fatal("error while updating table ItemsOnGround " + e, e);
        } finally {
            L2DatabaseFactory.close(con);
        }
    }

    // Add items to world
    Connection con = null;
    try {
        try {
            con = L2DatabaseFactory.getInstance().getConnection(con);
            Statement s = con.createStatement();
            ResultSet result;
            int count = 0;
            result = s.executeQuery(
                    "SELECT object_id,item_id,count,enchant_level,x,y,z,drop_time,equipable FROM itemsonground");
            while (result.next()) {
                L2ItemInstance item = new L2ItemInstance(result.getInt(1), result.getInt(2));
                L2World.getInstance().storeObject(item);
                item.setCount(result.getLong(3));
                item.setEnchantLevel(result.getInt(4));
                item.getPosition().setXYZ(result.getInt(5), result.getInt(6), result.getInt(7));
                item.setDropTime(result.getLong(8));
                if (result.getLong(8) == -1)
                    item.setProtected(true);
                else
                    item.setProtected(false);
                L2World.getInstance().addVisibleObject(item);
                _items.add(item);
                count++;
                // Add to ItemsAutoDestroy only items not protected
                if (result.getLong(8) > -1) {
                    ItemsAutoDestroyManager.tryAddItem(item);
                }
            }
            result.close();
            s.close();
            if (count > 0)
                _log.info("ItemsOnGroundManager: restored " + count + " items.");
            else
                _log.info("Initializing ItemsOnGroundManager.");
        } catch (Exception e) {
            _log.fatal("error while loading ItemsOnGround " + e, e);
        }
    } finally {
        L2DatabaseFactory.close(con);
    }

    if (Config.EMPTY_DROPPED_ITEM_TABLE_AFTER_LOAD)
        emptyTable();
}

From source file:net.codjo.dataprocess.server.treatmenthelper.TreatmentHelper.java

public static void insertRepositoryContent(Connection con, int repositoryId, String content)
        throws SQLException, TreatmentException, TransformerException {
    Document doc;/*from   w ww .j a v  a  2  s .c om*/
    try {
        doc = XMLUtils.parse(content);
    } catch (Exception ex) {
        throw new TreatmentException(ex);
    }
    PreparedStatement pStmt = con.prepareStatement(
            "insert into PM_REPOSITORY_CONTENT (REPOSITORY_CONTENT_ID, REPOSITORY_ID, TREATMENT_ID, CONTENT) values (?, ?, ?, ?)");
    try {
        NodeList nodes = doc.getElementsByTagName(DataProcessConstants.TREATMENT_ENTITY_XML);
        int nbNodes = nodes.getLength();
        for (int i = 0; i < nbNodes; i++) {
            Node node = nodes.item(i);
            String treatmentId = node.getAttributes().getNamedItem("id").getNodeValue();
            if (treatmentId.length() > 50) {
                throw new TreatmentException("La taille de l'identifiant d'un traitement ('" + treatmentId
                        + "') dpasse 50 caractres.");
            }

            String contentNode = XMLUtils.nodeToString(node);
            pStmt.setInt(1, SQLUtil.getNextId(con, "PM_REPOSITORY_CONTENT", "REPOSITORY_CONTENT_ID"));
            pStmt.setInt(2, repositoryId);
            pStmt.setString(3, treatmentId);
            pStmt.setString(4, contentNode);
            pStmt.executeUpdate();
        }
    } finally {
        pStmt.close();
    }
}

From source file:com.uit.anonymousidentity.Repository.IssuerKeys.IssuerJDBCTemplate.java

@Override
public void store(Issuer issuer) throws SQLException {
    String t_sql = "insert into %s (%s, %s, %s, %s) values ( ?, ?, ?, ? )";
    String sql = String.format(t_sql, TABLE_NAME, SID, BNCurveName, PK, SK);
    PreparedStatement pst = dataSource.getConnection().prepareStatement(sql);
    pst.setString(1, issuer.getSid());/*from   w w  w. j ava2s . c o m*/
    pst.setString(2, issuer.getCurve().getName());
    pst.setString(3, issuer.pk.toJSON(issuer.getCurve()));
    pst.setString(4, issuer.getSk().toJson(issuer.getCurve()));
    pst.executeUpdate();
    pst.close();

}

From source file:de.ingrid.iplug.dsc.index.mapper.DatabaseProfileMapper.java

@Override
public void map(SourceRecord record, ElasticDocument doc) {
    if (!(record instanceof DatabaseSourceRecord)) {
        throw new IllegalArgumentException("Record is no DatabaseRecord!");
    }//from   ww  w.  jav  a2  s.co  m

    Connection connection = (Connection) record.get(DatabaseSourceRecord.CONNECTION);
    try {
        String docId = (String) record.get(DatabaseSourceRecord.ID);
        ResultSet rs = connection
                .prepareStatement("SELECT value_string FROM sys_generic_key WHERE key_name='PROFILE'")
                .getResultSet();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        InputSource source = new InputSource(new StringReader(rs.getString(0)));
        org.w3c.dom.Document document = factory.newDocumentBuilder().parse(source);
        rs.close();
        NodeList nl = xPathUtils.getNodeList(document, "/PATH_TO_ADDITIONAL_FIELDS");
        for (int i = 0; i < nl.getLength(); i++) {
            Node n = nl.item(i);
            String dbName = xPathUtils.getString(n, "/XPATH_TO_DB_FIELD_NAME");
            String idxName = xPathUtils.getString(n, "/XPATH_TO_INDEX_FIELD_NAME");
            PreparedStatement ps = connection
                    .prepareStatement("SELECT value FROM additional_fields WHERE key_name='" + dbName
                            + "' AND WHERE doc_id='" + docId + "'");
            rs = ps.getResultSet();
            String value = rs.getString(0);
            rs.close();
            ps.close();
            doc.put(idxName, value);
        }
    } catch (Exception e) {
        log.error("Error mapping profile data.", e);
    }
}

From source file:adalid.util.sql.SqlUtil.java

protected void close(PreparedStatement statement) {
    if (statement != null) {
        try {//from   w  w w  . j a va2 s .c  o m
            statement.close();
        } catch (SQLException ex) {
            logger.fatal(statement, ex);
        }
    }
}

From source file:hu.petabyte.redflags.engine.gear.indicator.helper.KMonitorInstitutions.java

public void init() {
    if (initialized) {
        return;//from   ww  w .  j ava2s . c  o m
    }

    if (null == dbhost || null == dbname || null == dbuser || null == dbpass) {
        LOG.warn("K-Monitor Institutions component is not initialized.");
        return;
    }

    try {
        LOG.info("Connecting to K-Monitor database...");
        conn = DriverManager.getConnection(
                String.format("jdbc:mysql://%s/%s?useUnicode=true&characterEncoding=utf-8", dbhost, dbname),
                dbuser, dbpass);
        LOG.info("Querying institutions...");
        PreparedStatement ps = conn.prepareStatement("SELECT name FROM news_institutions");
        ps.execute();
        ResultSet rs = ps.getResultSet();
        while (rs.next()) {
            institutions.add(rs.getString(1));
        }
        rs.close();
        ps.close();
        LOG.info("We have {} institutions", institutions.size());
        conn.close();
    } catch (Exception e) {
        LOG.error("Failed to connect to KMDB.", e);
    }
    initialized = true;
}