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.nextep.designer.sqlclient.ui.services.impl.SQLClientService.java

@Override
public void deleteQueryValue(ISQLQuery query, ISQLRowResult row) throws SQLException {
    ISQLRowModificationStatus status = computeRowModificationStatus(query, row, -1);
    if (status.isModifiable()) {
        final ISQLResult result = query.getResult();
        final Connection conn = query.getConnection();
        final DatabaseMetaData md = conn.getMetaData();
        final String deleteStmt = buildDeleteStatement(status, md.getIdentifierQuoteString());
        PreparedStatement stmt = null;
        try {//ww w . j  a va2 s. co m
            stmt = conn.prepareStatement(deleteStmt);
            fillPreparedStatement(stmt, false, false, row, null);
            stmt.execute();
            if (stmt.getUpdateCount() > 0) {
                result.removeRow(row);
            }
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }

    }

}

From source file:fr.gael.dhus.database.liquibase.CopyProductImages.java

@Override
public void execute(Database database) throws CustomChangeException {
    PreparedStatement products = null;
    ResultSet products_res = null;
    JdbcConnection db_connection = (JdbcConnection) database.getConnection();
    try {//from  www.  j  av a2 s .c om
        products = db_connection.prepareStatement("SELECT ID,QUICKLOOK,THUMBNAIL FROM PRODUCTS");
        products_res = products.executeQuery();
        while (products_res.next()) {
            PreparedStatement copy_blob_stmt = null;
            ResultSet generated_key_res = null;
            try {
                Blob ql = (Blob) products_res.getObject("QUICKLOOK");
                Blob th = (Blob) products_res.getObject("THUMBNAIL");
                Long pid = products_res.getLong("ID");

                // No images: add false flags
                if ((ql == null) && (th == null)) {
                    PreparedStatement product_flags_stmt = null;
                    // Add related flags
                    try {
                        product_flags_stmt = db_connection.prepareStatement(
                                "UPDATE PRODUCTS SET THUMBNAIL_FLAG=?,QUICKLOOK_FLAG=? " + "WHERE ID=?");
                        product_flags_stmt.setBoolean(1, false);
                        product_flags_stmt.setBoolean(2, false);
                        product_flags_stmt.setLong(3, pid);
                        product_flags_stmt.execute();
                    } finally {
                        if (product_flags_stmt != null)
                            try {
                                product_flags_stmt.close();
                            } catch (Exception e) {
                                logger.warn("Cannot close Statement !");
                            }
                    }
                    continue;
                }

                copy_blob_stmt = db_connection.prepareStatement(
                        "INSERT INTO PRODUCT_IMAGES (QUICKLOOK,THUMBNAIL) " + "VALUES (?,?)",
                        Statement.RETURN_GENERATED_KEYS);

                copy_blob_stmt.setBlob(1, ql);
                copy_blob_stmt.setBlob(2, th);
                copy_blob_stmt.execute();

                generated_key_res = copy_blob_stmt.getGeneratedKeys();
                if (generated_key_res.next()) {
                    PreparedStatement set_product_image_id_stmt = null;
                    Long iid = generated_key_res.getLong(1);

                    // Add ProductImages "IMAGES" entry in product
                    try {
                        set_product_image_id_stmt = db_connection
                                .prepareStatement("UPDATE PRODUCTS SET IMAGES_ID=?, THUMBNAIL_FLAG=?, "
                                        + "QUICKLOOK_FLAG=?  WHERE ID=?");
                        set_product_image_id_stmt.setLong(1, iid);
                        set_product_image_id_stmt.setBoolean(2, th != null);
                        set_product_image_id_stmt.setBoolean(3, ql != null);
                        set_product_image_id_stmt.setLong(4, pid);
                        set_product_image_id_stmt.execute();
                    } finally {
                        if (set_product_image_id_stmt != null)
                            try {
                                set_product_image_id_stmt.close();
                            } catch (Exception e) {
                                logger.warn("Cannot close Statement !");
                            }
                    }
                } else {
                    logger.error("Cannot retrieve Image primary key for " + "product ID #"
                            + products_res.getLong("ID"));
                }
            } finally {
                if (generated_key_res != null)
                    try {
                        generated_key_res.close();
                    } catch (Exception e) {
                        logger.warn("Cannot close ResultSet !");
                    }
                if (copy_blob_stmt != null)
                    try {
                        copy_blob_stmt.close();
                    } catch (Exception e) {
                        logger.warn("Cannot close Statement !");
                    }
            }
        }
    } catch (Exception e) {
        throw new CustomChangeException("Cannot move Blobs from product", e);
    } finally {
        if (products_res != null) {
            try {
                products_res.close();
            } catch (Exception e) {
                logger.warn("Cannot close ResultSet !");
            }
        }
        if (products != null) {
            try {
                products.close();
            } catch (Exception e) {
                logger.warn("Cannot close Statement !");
            }
        }
        //if (db_connection!=null) try { db_connection.close (); }
        // catch (Exception e) {}
    }
}

From source file:com.l2jfree.gameserver.communitybbs.bb.Forum.java

/**
 *
 *///  w  w  w.j a  va 2s .c o m
public void insertIntoDb() {
    Connection con = null;
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(
                "INSERT INTO forums (forum_id,forum_name,forum_parent,forum_post,forum_type,forum_perm,forum_owner_id) VALUES (?,?,?,?,?,?,?)");
        statement.setInt(1, _forumId);
        statement.setString(2, _forumName);
        statement.setInt(3, _fParent.getID());
        statement.setInt(4, _forumPost);
        statement.setInt(5, _forumType);
        statement.setInt(6, _forumPerm);
        statement.setInt(7, _ownerID);
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.warn("error while saving new Forum to db ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.alkacon.opencms.counter.CmsCounterManager.java

/**
 * This function deletes a counter entry in the database.<p>
 * /* w  ww .j a  v a2 s .  c om*/
 * @param entryKey the counter entry which should be deleted
 * 
 * @return <code>true</code> if successfully deleting otherwise <code>false</code>
 * 
 * @throws CmsException if an error occurred
 */
public boolean deleteCounter(String entryKey) throws CmsException {

    boolean result = false;
    Connection con = null;
    PreparedStatement statement = null;

    // check if the parameters are empty
    if (CmsStringUtil.isEmptyOrWhitespaceOnly(entryKey)) {
        return result;
    }

    try {
        // get connection and execute the delete query
        con = CmsDbUtil.getInstance().getConnection(m_connectionPool);
        statement = con.prepareStatement(C_DELETE_COUNTER_ENTRY);
        statement.setString(1, entryKey);
        result = statement.execute();

    } catch (SQLException ex) {
        if (LOG.isErrorEnabled()) {
            LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_ACCESSING_DB_1, C_COUNTER_TABLE), ex);
        }
        throw new CmsException(Messages.get().container(Messages.LOG_ERROR_DELETE_COUNTER_1, entryKey));
    } finally {
        CmsDbUtil.getInstance().closeConnection(null, statement, con);
    }
    return result;
}

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

public void testUnknownDataType() throws SQLException {
    assertThrows(SQLErrorCode.UNKNOWN_DATA_TYPE_1, conn).prepareStatement("SELECT * FROM (SELECT ? FROM DUAL)");
    PreparedStatement prep = conn.prepareStatement("SELECT -?");
    prep.setInt(1, 1);/*from ww w .j  av a  2 s . c o m*/
    prep.execute();
    prep = conn.prepareStatement("SELECT ?-?");
    prep.setInt(1, 1);
    prep.setInt(2, 2);
    prep.execute();
}

From source file:com.netspective.axiom.sql.Query.java

protected boolean checkRecordExistsLogStatistics(ConnectionContext cc, Object[] overrideParams)
        throws NamingException, SQLException {
    if (log.isTraceEnabled())
        trace(cc, overrideParams);/* w w w . j  av a  2  s .  c om*/
    QueryExecutionLogEntry logEntry = execLog.createNewEntry(cc, this.getQualifiedName());
    try {
        PreparedStatement stmt = createStatement(cc, overrideParams, false, logEntry);

        logEntry.registerExecSqlBegin();
        boolean executeStmtResult = stmt.execute();
        logEntry.registerExecSqlEndSuccess();
        boolean exists = executeStmtResult && stmt.getResultSet().next();
        stmt.close();
        return exists;
    } catch (SQLException e) {
        logEntry.registerExecSqlEndFailed();
        log.error(createExceptionMessage(cc, overrideParams), e);
        throw e;
    } finally {
        logEntry.finalize(cc, log);
    }
}

From source file:com.l2jfree.gameserver.model.clan.L2ClanMember.java

public void updateSubPledgeType() {
    Connection con = null;//from   w w w . ja v a  2 s . com

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement("UPDATE characters SET subpledge=? WHERE charId=?");
        statement.setLong(1, _subPledgeType);
        statement.setInt(2, getObjectId());
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.warn("could not set char subpledge:", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.netspective.axiom.sql.Query.java

protected QueryResultSet executeAndRecordStatistics(ConnectionContext cc, Object[] overrideParams,
        boolean scrollable) throws NamingException, SQLException {
    if (log.isTraceEnabled())
        trace(cc, overrideParams);//from   w  w  w  .  ja  v  a  2s. c  o  m
    QueryExecutionLogEntry logEntry = execLog.createNewEntry(cc, this.getQualifiedName());
    try {
        PreparedStatement stmt = createStatement(cc, overrideParams, scrollable, logEntry);

        logEntry.registerExecSqlBegin();
        boolean executeStmtResult = stmt.execute();
        logEntry.registerExecSqlEndSuccess();
        return new QueryResultSet(this, cc, executeStmtResult, stmt.getResultSet(), logEntry);
    } catch (SQLException e) {
        logEntry.registerExecSqlEndFailed();
        log.error(createExceptionMessage(cc, overrideParams), e);
        throw e;
    } finally {
        logEntry.finalize(cc, log);
    }
}

From source file:jp.primecloud.auto.tool.management.db.SQLExecuter.java

public void executePrepared(String sql, String... params) throws SQLException, Exception {
    Connection con = null;//  w ww.  j  av  a2s.co  m
    PreparedStatement ps = null;
    ResultSet rs = null;
    // ??
    String logSQL = passwordMask(sql);
    log.info("[" + logSQL + "] ???");
    try {
        con = dbConnector.getConnection();
        ps = con.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            ps.setString(i + 1, params[i]);
        }
        ps.execute();
        log.info("[" + logSQL + "] ????");
    } catch (SQLException e) {
        log.error(passwordMask(e.getMessage()), e);
        throw new SQLException(e);
    } catch (Exception e) {
        log.error(passwordMask(e.getMessage()), e);
        throw new Exception(e);
    } finally {
        try {
            dbConnector.closeConnection(con, ps, rs);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java

@Test
public void testObjectTimestamp() throws Exception {
    Statement stmt = con.createStatement();
    java.util.Date now = new java.util.Date();

    // Create the target Column family
    //String createCF = "CREATE COLUMNFAMILY t74 (id BIGINT PRIMARY KEY, col1 TIMESTAMP)";        
    String createCF = "CREATE COLUMNFAMILY t74 (id BIGINT PRIMARY KEY, col1 TIMESTAMP)";

    stmt.execute(createCF);/*from   w  w w.j ava  2 s .  c o  m*/
    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager
            .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS));

    Statement statement = con.createStatement();

    String insert = "INSERT INTO t74 (id, col1) VALUES (?, ?);";

    PreparedStatement pstatement = con.prepareStatement(insert);
    pstatement.setLong(1, 1L);
    pstatement.setObject(2, new Timestamp(now.getTime()), Types.TIMESTAMP);
    pstatement.execute();

    ResultSet result = statement.executeQuery("SELECT * FROM t74;");

    assertTrue(result.next());
    assertEquals(1L, result.getLong(1));

    // try reading Timestamp directly
    Timestamp stamp = result.getTimestamp(2);
    assertEquals(now, stamp);

    // try reading Timestamp as an object
    stamp = result.getObject(2, Timestamp.class);
    assertEquals(now, stamp);

    System.out.println(resultToDisplay(result, 74, "current date"));

}