Example usage for java.sql PreparedStatement setBoolean

List of usage examples for java.sql PreparedStatement setBoolean

Introduction

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

Prototype

void setBoolean(int parameterIndex, boolean x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java boolean value.

Usage

From source file:org.kawanfw.test.api.client.InsertAndUpdateBlobTestNew.java

/**
 * Insert a blob// ww  w.j  av  a 2s .c  o m
 * 
 * @throws Exception
 *             it any Exception occurs
 */
public void insertLoopPrepStatement(Connection connection, int numberToInsert, File blobFile) throws Exception {

    // We can now use our Remote JDBC Connection as a regular Connection!
    connection.setAutoCommit(false);

    // We will do all our remote insert in a SQL Transaction
    try {

        String sql = "insert into orderlog values ( ?, ?, ?, ?, ?, ?, ?, ?, ? )";

        // Create a new Prepared Statement
        PreparedStatement prepStatement = null;

        MessageDisplayer.display("");
        MessageDisplayer.display("Inserting " + numberToInsert + " orderlog...");

        for (int customerId = 1; customerId < numberToInsert + 1; customerId++) {
            int i = 1;
            long theTime = new java.util.Date().getTime();

            // We will insert a Blob (the image of the product).
            // The transfer will be done in streaming both on the client
            // and on the Servlet Server: we can upload/download very big
            // files.

            InputStream in = null;
            OutputStream out = null;

            try {
                in = new FileInputStream(blobFile);
                Blob blob = connection.createBlob();
                out = blob.setBinaryStream(1);
                IOUtils.copy(in, out);

                prepStatement = connection.prepareStatement(sql);

                prepStatement.setInt(i++, customerId);
                prepStatement.setInt(i++, customerId);
                prepStatement.setString(i++, "Item Description No " + customerId);
                prepStatement.setBigDecimal(i++, new BigDecimal(customerId));
                prepStatement.setDate(i++, new java.sql.Date(theTime));
                prepStatement.setTimestamp(i++, new Timestamp(theTime));
                prepStatement.setBlob(i++, blob);

                SqlUtil sqlUtil = new SqlUtil(connection);
                if (sqlUtil.isIngres()) {
                    prepStatement.setInt(i++, 0);
                } else {
                    prepStatement.setBoolean(i++, false);
                }

                prepStatement.setInt(i++, customerId);

                // SystemOutHandle.display("Before executeUpdate...");
                prepStatement.executeUpdate();

                // Close and free are important to delete temp files
                prepStatement.close();
                blob.free();
            } finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

        }

        // We do either everything in a single transaction or nothing
        connection.commit(); // Commit is propagated on Server
        MessageDisplayer.display("Remote Commit Done on AceQL Server!");
    } catch (Exception e) {
        connection.rollback();
        throw e;
    } finally {
        connection.setAutoCommit(true);
    }

}

From source file:org.openmrs.util.databasechange.CreateCodedOrderFrequencyForDrugOrderFrequencyChangeset.java

private void insertUniqueFrequencies(JdbcConnection connection, Set<String> uniqueFrequencies)
        throws CustomChangeException, SQLException, DatabaseException {
    PreparedStatement insertOrderFrequencyStatement = null;
    Boolean autoCommit = null;//from ww  w  . j  a v a  2 s  .c o  m
    try {
        autoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        insertOrderFrequencyStatement = connection.prepareStatement("insert into order_frequency "
                + "(concept_id, creator, date_created, retired, uuid) values (?, ?, ?, ?, ?)");

        Date date = new Date(new java.util.Date().getTime());

        for (String frequency : uniqueFrequencies) {
            if (StringUtils.isBlank(frequency)) {
                continue;
            }

            Integer conceptIdForFrequency = UpgradeUtil.getConceptIdForUnits(frequency);
            if (conceptIdForFrequency == null) {
                throw new CustomChangeException("No concept mapping found for frequency: " + frequency);
            }

            Integer orderFrequencyId = UpgradeUtil.getOrderFrequencyIdForConceptId(
                    connection.getUnderlyingConnection(), conceptIdForFrequency);
            if (orderFrequencyId != null) {
                //a single concept is mapped to more than one text or there is an order frequency already
                continue;
            }

            //Generating UUID for order frequency. Generated UUIDs will be the same if concepts UUIDs are the same.
            String uuid = UpgradeUtil.getConceptUuid(connection.getUnderlyingConnection(),
                    conceptIdForFrequency);
            uuid += "-6925ebb0-7c69-11e3-baa7-0800200c9a66"; //Adding random value for order frequency
            uuid = UUID.nameUUIDFromBytes(uuid.getBytes()).toString();

            insertOrderFrequencyStatement.setInt(1, conceptIdForFrequency);
            insertOrderFrequencyStatement.setInt(2, 1);
            insertOrderFrequencyStatement.setDate(3, date);
            insertOrderFrequencyStatement.setBoolean(4, false);
            insertOrderFrequencyStatement.setString(5, uuid);

            insertOrderFrequencyStatement.executeUpdate();
            insertOrderFrequencyStatement.clearParameters();
        }
        connection.commit();
    } catch (DatabaseException e) {
        handleError(connection, e);
    } catch (SQLException e) {
        handleError(connection, e);
    } finally {
        if (autoCommit != null) {
            connection.setAutoCommit(autoCommit);
        }
        if (insertOrderFrequencyStatement != null) {
            insertOrderFrequencyStatement.close();
        }
    }
}

From source file:org.kawanfw.test.api.client.InsertAndUpdateBlobTestPsqlOID.java

/**
 * Insert a blob/* w  ww  .ja v a 2  s .  co m*/
 * 
 * @throws Exception
 *             it any Exception occurs
 */
public void insertLoopPrepStatement(Connection connection, int numberToInsert, File blobFile) throws Exception {

    // We can now use our Remote JDBC Connection as a regular Connection!
    connection.setAutoCommit(false);

    // We will do all our remote insert in a SQL Transaction
    try {

        String sql = "insert into orderlog_2 values ( ?, ?, ?, ?, ?, ?, ?, ?, ? )";

        // Create a new Prepared Statement
        PreparedStatement prepStatement = null;

        MessageDisplayer.display("");
        MessageDisplayer.display("Inserting " + numberToInsert + " orderlog_2...");

        for (int customerId = 1; customerId < numberToInsert + 1; customerId++) {
            int i = 1;
            long theTime = new java.util.Date().getTime();

            // We will insert a Blob (the image of the product).
            // The transfer will be done in streaming both on the client
            // and on the Servlet Server: we can upload/download very big
            // files.

            // InputStream in = new BufferedInputStream(new
            // FileInputStream(blobFile));
            InputStream in = new FileInputStream(blobFile);

            prepStatement = connection.prepareStatement(sql);

            prepStatement.setInt(i++, customerId);
            prepStatement.setInt(i++, customerId);
            prepStatement.setString(i++, "Item Description No " + customerId);
            prepStatement.setBigDecimal(i++, new BigDecimal(customerId));
            prepStatement.setDate(i++, new java.sql.Date(theTime));
            prepStatement.setTimestamp(i++, new Timestamp(theTime));

            prepStatement.setBinaryStream(i++, in, (int) blobFile.length());

            // prepStatement.setBoolean(i++, false);
            SqlUtil sqlUtil = new SqlUtil(connection);
            if (sqlUtil.isIngres() || sqlUtil.isPostgreSQL()) {
                prepStatement.setInt(i++, 0);
            } else {
                prepStatement.setBoolean(i++, false);
            }

            prepStatement.setInt(i++, customerId);

            // SystemOutHandle.display("Before executeUpdate...");
            prepStatement.executeUpdate();
            prepStatement.close();

            in.close();

        }

        // We do either everything in a single transaction or nothing
        connection.commit(); // Commit is propagated on Server
        MessageDisplayer.display("Remote Commit Done on AceQL Server!");
    } catch (Exception e) {
        connection.rollback();
        throw e;
    } finally {
        connection.setAutoCommit(true);
    }

}

From source file:org.methodize.nntprss.feed.db.JdbcChannelDAO.java

public void saveConfiguration(NNTPServer nntpServer) {
    Connection conn = null;/*from   w  w w  .  ja  va2  s.c om*/
    PreparedStatement ps = null;

    try {
        conn = DriverManager.getConnection(JdbcChannelDAO.POOL_CONNECT_STRING);
        ps = conn.prepareStatement("UPDATE " + TABLE_CONFIG + " "
                + "SET contentType = ?, nntpSecure = ?, footnoteUrls = ?, hostName = ?");

        int paramCount = 1;
        ps.setInt(paramCount++, nntpServer.getContentType());
        ps.setBoolean(paramCount++, nntpServer.isSecure());
        ps.setBoolean(paramCount++, nntpServer.isFootnoteUrls());
        ps.setString(paramCount++, nntpServer.getHostName());
        ps.executeUpdate();

    } catch (SQLException se) {
        throw new RuntimeException(se);
    } finally {
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException se) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
        }
    }

}

From source file:com.enonic.vertical.engine.handlers.SectionHandler.java

public void updateSectionContent(User user, int sectionKey, int contentKey, int order, boolean approved,
        SectionContentKey scKey, boolean checkAccess)
        throws VerticalUpdateException, VerticalSecurityException {
    if (checkAccess) {
        checkSectionApproveAccess(user, sectionKey);
    }/*from  w  w w .j av  a2  s  . c o  m*/

    Connection con = null;
    PreparedStatement preparedStmt = null;

    if (scKey == null) {
        scKey = getSectionContentKey(sectionKey, contentKey);
    }
    try {
        con = getConnection();
        StringBuffer sql = XDG.generateUpdateSQL(db.tSectionContent2);

        //            UPDATE tSectionContent2
        //            SET sco_con_lKey = ?, sco_mei_lKey = ?, sco_lOrder = ?, sco_bApproved = ?, sco_dteTimestamp = @currentTimestamp@
        //            WHERE sco_lkey = ?

        preparedStmt = con.prepareStatement(sql.toString());
        preparedStmt.setInt(1, contentKey);
        preparedStmt.setInt(2, sectionKey);
        preparedStmt.setInt(3, order);
        preparedStmt.setBoolean(4, approved);
        preparedStmt.setInt(5, scKey.toInt());

        int result = preparedStmt.executeUpdate();
        if (result == 0) {
            String message = "Failed to add content to section.";
            VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
        }
    } catch (SQLException sqle) {
        String message = "Failed to update content section: %t";
        VerticalEngineLogger.errorUpdate(this.getClass(), 1, message, sqle);
    } finally {
        close(preparedStmt);
        close(con);
    }
}

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

/**
 * Description of the Method//from  w w  w .  j  a  v a2  s.  com
 *
 * @param db Description of Parameter
 * @return Description of the Returned Value
 * @throws SQLException Description of Exception
 */
public int update(Connection db) throws SQLException {
    if (this.getId() == -1) {
        throw new SQLException("ID was not specified");
    }
    if (!isValid()) {
        return -1;
    }
    int resultCount = 0;
    boolean commit = db.getAutoCommit();
    try {
        if (commit) {
            db.setAutoCommit(false);
        }
        int i = 0;
        // NOTE: Do not update the "modified" field because it is used for file paths
        PreparedStatement pst = db.prepareStatement("UPDATE project_files "
                + "SET subject = ?, client_filename = ?, default_file = ?, comment = ?, featured_file = ? "
                + "WHERE item_id = ? ");
        pst.setString(++i, subject);
        pst.setString(++i, clientFilename);
        pst.setBoolean(++i, defaultFile);
        pst.setString(++i, comment);
        pst.setBoolean(++i, featuredFile);
        pst.setInt(++i, this.getId());
        resultCount = pst.executeUpdate();
        pst.close();
        // Set default
        if (defaultFile) {
            updateDefaultRecord(db, linkModuleId, linkItemId, id);
        }
        // Retrieve any versions
        this.buildVersionList(db);
        // Update version info for the corresponding file item version
        for (FileItemVersion latestVersion : versionList) {
            if (Double.toString(this.version).equals(Double.toString(latestVersion.getVersion()))) {
                latestVersion.setClientFilename(this.getClientFilename());
                latestVersion.setSubject(this.getSubject());
                latestVersion.setComment(this.getComment());
                latestVersion.update(db);
                break;
            }
        }
    } catch (Exception e) {
        if (commit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (commit) {
            db.setAutoCommit(true);
        }
    }
    return resultCount;
}

From source file:edu.umd.cs.marmoset.modelClasses.TestOutcome.java

/**
* Populated a prepared statement starting at a given index with all of the fields
* of this model class.// w ww  .  j a v  a 2  s  .  co  m
* @param stmt the PreparedStatement
* @param index the starting index
* @return the index of the next open slot in the prepared statement
* @throws SQLException
*/
int putValues(PreparedStatement stmt, int index) throws SQLException {
    limitSizes();
    stmt.setInt(index++, getTestRunPK());
    stmt.setString(index++, getTestType().name());
    stmt.setString(index++, getTestNumber());
    stmt.setString(index++, getOutcome());
    stmt.setInt(index++, getPointValue());
    stmt.setString(index++, getTestName());
    stmt.setString(index++, getShortTestResult());
    stmt.setString(index++, longTestResult);
    stmt.setString(index++, getExceptionClassName());
    stmt.setString(index++, (getCoarsestCoverageLevel() != null) ? getCoarsestCoverageLevel().toString()
            : CoverageLevel.NONE.toString());
    stmt.setBoolean(index++, getExceptionSourceCoveredElsewhere());
    stmt.setObject(index++, getDetails());
    stmt.setInt(index++, getExecutionTimeMillis());
    return index;
}

From source file:com.uas.document.DocumentDAO.java

@Override
public DocumentDTO updateDocumentDeleted(DocumentDTO dDto) {

    //System.out.println("dDto.getDeleted() : " + dDto.getDeleted());
    DocumentDTO dtoViejo = getDocument(dDto);

    DocumentDTO objectDto = null;/*from  ww  w. j  a  va 2s.c o  m*/

    ResultSet rs = null;
    Connection c = null;
    PreparedStatement preparedStmt = null;

    try {
        c = DataSourceSingleton.getInstance().getConnection();
        String SQL = "update \"public\".\"document\" set \"deleted\"=? where \"id\"=? ";
        preparedStmt = c.prepareStatement(SQL);
        preparedStmt.setBoolean(1, dDto.getDeleted());
        preparedStmt.setInt(2, dDto.getId());
        preparedStmt.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (c != null) {
                c.close();
            }
            if (preparedStmt != null) {
                preparedStmt.close();
            }

        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }
    return dDto;
}

From source file:fi.helsinki.cs.iot.kahvihub.database.sqliteJdbc.IotHubDatabaseSqliteJDBCImpl.java

@Override
public Service addService(ServiceInfo serviceInfo, String name, String metadata, String config,
        boolean bootAtStartup) {
    Service service = null;//from   w ww .  j  av a 2s  .  co m
    if (serviceInfo == null || name == null) {
        Log.e(TAG, "One cannot create a service where the serviceInfo is null, or name is null");
        return null;
    }
    try {
        checkOpenness();
        connection.setAutoCommit(false);
        String sqlInsert = "INSERT INTO " + IotHubDataHandler.TABLE_SERVICE + "("
                + IotHubDataHandler.KEY_SERVICE_NAME + "," + IotHubDataHandler.KEY_SERVICE_METADATA + ","
                + IotHubDataHandler.KEY_SERVICE_SERVICE_INFO + "," + IotHubDataHandler.KEY_SERVICE_CONFIG + ","
                + IotHubDataHandler.KEY_SERVICE_BOOT_AT_STARTUP + ") VALUES (?,?,?,?,?)";
        PreparedStatement psInsert = connection.prepareStatement(sqlInsert, Statement.RETURN_GENERATED_KEYS);
        psInsert.setString(1, name);
        psInsert.setString(2, metadata);
        psInsert.setLong(3, serviceInfo.getId());
        psInsert.setString(4, config);
        psInsert.setBoolean(5, bootAtStartup);
        psInsert.executeUpdate();
        ResultSet genKeys = psInsert.getGeneratedKeys();
        if (genKeys.next()) {
            long insertId = genKeys.getLong(1);
            //At point we should have everything set so it is time to retrieve the plugin from the database
            //Log.d(TAG, "Now i will try to collect the service " + insertId + " that was just added to the db");
            service = getService(insertId);
            if (service == null) {
                Log.e(TAG, "The service " + name + " should not be null");
            }
        } else {
            Log.e(TAG, "The insert of service " + name + " did not work");
        }
        genKeys.close();
        psInsert.close();
    } catch (SQLException | IotHubDatabaseException e) {
        e.printStackTrace();
        service = null;
    }
    try {
        if (service == null) {
            connection.rollback();
        }
        connection.commit();
        connection.setAutoCommit(true);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return service;
}

From source file:fi.helsinki.cs.iot.kahvihub.database.sqliteJdbc.IotHubDatabaseSqliteJDBCImpl.java

@Override
public Feature addFeature(Enabler enabler, String name, String type) {
    Feature feature = null;/*w w w . j  a va 2 s . c  om*/
    if (enabler == null || name == null || type == null) {
        Log.e(TAG, "One cannot create a feature where the enable is null, name is null or with no type");
        return null;
    }
    try {
        checkOpenness();
        connection.setAutoCommit(false);
        String sqlFeatureInsert = "INSERT INTO " + IotHubDataHandler.TABLE_FEATURE + "("
                + IotHubDataHandler.KEY_FEATURE_ENABLER_ID + "," + IotHubDataHandler.KEY_FEATURE_NAME + ","
                + IotHubDataHandler.KEY_FEATURE_TYPE + "," + IotHubDataHandler.KEY_FEATURE_IS_FEED
                + ") VALUES (?,?,?,?)";
        PreparedStatement psFeatureInsert = connection.prepareStatement(sqlFeatureInsert,
                Statement.RETURN_GENERATED_KEYS);
        psFeatureInsert.setLong(1, enabler.getId());
        psFeatureInsert.setString(2, name);
        psFeatureInsert.setString(3, type);
        psFeatureInsert.setBoolean(4, false); //An added feature is never a feed
        psFeatureInsert.executeUpdate();
        ResultSet genKeysFeature = psFeatureInsert.getGeneratedKeys();
        if (genKeysFeature.next()) {
            long insertIdFeature = genKeysFeature.getLong(1);
            //At point we should have everything set so it is time to retrieve the plugin from the database
            //Log.d(TAG, "Now i will try to collect the feature that was just added to the db");
            feature = getFeature(insertIdFeature);
            if (feature == null) {
                Log.e(TAG, "The feature should not be null");
            }
        } else {
            Log.e(TAG, "The insert of feature " + name + " did not work");
        }
        genKeysFeature.close();
        psFeatureInsert.close();
    } catch (SQLException | IotHubDatabaseException e) {
        e.printStackTrace();
        feature = null;
    }
    try {
        if (feature == null) {
            connection.rollback();
        }
        connection.commit();
        connection.setAutoCommit(true);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return feature;
}