Example usage for java.sql PreparedStatement setBinaryStream

List of usage examples for java.sql PreparedStatement setBinaryStream

Introduction

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

Prototype

void setBinaryStream(int parameterIndex, java.io.InputStream x, long length) throws SQLException;

Source Link

Document

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

Usage

From source file:org.quartz.impl.jdbcjobstore.PointbaseDelegate.java

/**
 * <p>//w ww  . j  a  v a  2  s  . c  om
 * Update the job detail record.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param job
 *          the job to update
 * @return number of rows updated
 * @throws IOException
 *           if there were problems serializing the JobDataMap
 */
public int updateJobDetail(Connection conn, JobDetail job) throws IOException, SQLException {
    //log.debug( "Updating job detail " + job );
    ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap());
    int len = baos.toByteArray().length;
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

    PreparedStatement ps = null;

    int insertResult = 0;

    try {
        ps = conn.prepareStatement(rtp(UPDATE_JOB_DETAIL));
        ps.setString(1, job.getDescription());
        ps.setString(2, job.getJobClass().getName());
        setBoolean(ps, 3, job.isDurable());
        setBoolean(ps, 4, job.isVolatile());
        setBoolean(ps, 5, job.isStateful());
        setBoolean(ps, 6, job.requestsRecovery());
        ps.setBinaryStream(7, bais, len);
        ps.setString(8, job.getName());
        ps.setString(9, job.getGroup());

        insertResult = ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }

    if (insertResult > 0) {
        deleteJobListeners(conn, job.getName(), job.getGroup());

        String[] jobListeners = job.getJobListenerNames();
        for (int i = 0; jobListeners != null && i < jobListeners.length; i++) {
            insertJobListener(conn, job, jobListeners[i]);
        }
    }

    return insertResult;
}

From source file:Formulario.CapturaHuella.java

public void guardarHuella(String nom) {

    String rut = jTextField1.getText();
    if (rut.isEmpty()) {
        EnviarTexto("No se ha ingresado el rut del usuario");
    } else {/*  ww  w  .ja va2  s  . c  o  m*/

        try {

            Connection c = cn.conectar();
            PreparedStatement buscar = c.prepareStatement(
                    "select count(*) numero from municipalidad.foto_contribuyente where rut = ?");
            String rut_form = Metodos_Rut.formatear(nom);
            buscar.setString(1, rut_form);
            ResultSet rs = buscar.executeQuery();
            if (rs.next()) {

                Object numero = rs.getObject("numero");
                int resultado = Integer.parseInt(numero.toString());
                if (resultado == 0) {
                    System.out.println("tienes que insertar");
                    PreparedStatement insertar = c.prepareStatement(
                            "INSERT INTO municipalidad.foto_contribuyente(rut,pulgar_der) values(?,?)");
                    insertar.setString(1, rut_form);
                    insertar.setBinaryStream(2, fis, longitudBytes);
                    insertar.execute();
                    insertar.close();
                    JOptionPane.showMessageDialog(null, "Huella Guardada Correctamente");

                } else {
                    PreparedStatement guardarStmt = c.prepareStatement(
                            " update municipalidad.foto_contribuyente set pulgar_der = ?  where rut= ?");
                    guardarStmt.setBinaryStream(1, fis, longitudBytes);
                    guardarStmt.setString(2, nom);

                    //Ejecuta la sentencia
                    guardarStmt.execute();
                    guardarStmt.close();
                    JOptionPane.showMessageDialog(null, "Huella Guardada Correctamente");
                }

            }

            //SQL AQUI
            //PreparedStatement guardarStmt = c.prepareStatement("INSERT INTO somhue(huenombre, huehuella) values(?,?)");//AQUI SQL!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //AQUI
            // PreparedStatement guardarStmt = c.prepareStatement("INSERT INTO municipalidad.foto_contribuyente(pulgar_der) values(?) WHERE rut=?");
            //            cn.desconectar();
            btnGuardar.setEnabled(false);

        } catch (SQLException ex) {
            //Si ocurre un error lo indica en la consola
            System.err.println("Error al guardar los datos de la huella.");
        } finally {
            cn.desconectar();
        }
    }
}

From source file:org.quartz.impl.jdbcjobstore.PointbaseDelegate.java

/**
 * <p>//from   ww  w  .  java 2 s  . co  m
 * Insert the job detail record.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param job
 *          the job to insert
 * @return number of rows inserted
 * @throws IOException
 *           if there were problems serializing the JobDataMap
 */
public int insertJobDetail(Connection conn, JobDetail job) throws IOException, SQLException {
    //log.debug( "Inserting JobDetail " + job );
    ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap());
    int len = baos.toByteArray().length;
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

    PreparedStatement ps = null;

    int insertResult = 0;

    try {
        ps = conn.prepareStatement(rtp(INSERT_JOB_DETAIL));
        ps.setString(1, job.getName());
        ps.setString(2, job.getGroup());
        ps.setString(3, job.getDescription());
        ps.setString(4, job.getJobClass().getName());
        setBoolean(ps, 5, job.isDurable());
        setBoolean(ps, 6, job.isVolatile());
        setBoolean(ps, 7, job.isStateful());
        setBoolean(ps, 8, job.requestsRecovery());
        ps.setBinaryStream(9, bais, len);

        insertResult = ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }

    if (insertResult > 0) {
        String[] jobListeners = job.getJobListenerNames();
        for (int i = 0; jobListeners != null && i < jobListeners.length; i++) {
            insertJobListener(conn, job, jobListeners[i]);
        }
    }

    return insertResult;
}

From source file:org.rhq.enterprise.server.plugin.ServerPluginsBean.java

/**
 * This will write the contents of the given plugin file to the database.
 * This will assume the MD5 in the database is already correct, so this
 * method will not take the time to calculate the MD5 again.
 *
 * @param id the ID of the plugin whose content is being updated
 * @param file the plugin file whose content will be streamed to the database
 *
 * @throws Exception// w w w  .ja  va  2 s  . c o m
 */
private void streamPluginFileContentToDatabase(int id, File file) throws Exception {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    FileInputStream fis = new FileInputStream(file);
    try {

        conn = this.dataSource.getConnection();
        ps = conn.prepareStatement("UPDATE " + ServerPlugin.TABLE_NAME + " SET CONTENT = ? WHERE ID = ?");
        BufferedInputStream bis = new BufferedInputStream(fis);
        try {
            ps.setBinaryStream(1, bis, (int) file.length());
            ps.setInt(2, id);
            int updateResults = ps.executeUpdate();
            if (updateResults != 1) {
                throw new Exception("Failed to update content for plugin [" + id + "] from [" + file + "]");
            }
        } finally {
            bis.close();
        }
    } finally {
        JDBCUtil.safeClose(conn, ps, rs);
        fis.close();
    }
    return;
}

From source file:org.rhq.enterprise.server.plugin.ServerPluginManagerBean.java

/**
 * This will write the contents of the given plugin file to the database.
 * This will assume the MD5 in the database is already correct, so this
 * method will not take the time to calculate the MD5 again.
 *
 * @param id the ID of the plugin whose content is being updated
 * @param file the plugin file whose content will be streamed to the database
 *
 * @throws Exception//from w w w.j a va 2 s  .  com
 */
private void streamPluginFileContentToDatabase(int id, File file) throws Exception {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    FileInputStream fis = new FileInputStream(file);
    try {

        conn = this.dataSource.getConnection();
        ps = conn.prepareStatement("UPDATE " + ServerPlugin.TABLE_NAME + " SET CONTENT = ? WHERE ID = ?");
        BufferedInputStream bis = new BufferedInputStream(fis);
        try {
            ps.setBinaryStream(1, bis, (int) file.length());
            ps.setInt(2, id);
            int updateResults = ps.executeUpdate();
            if (updateResults != 1) {
                throw new Exception("Failed to update content for plugin [" + id + "] from [" + file + "]");
            }
        } finally {
            bis.close();
        }
    } finally {
        JDBCUtil.safeClose(conn, ps, rs);
        StreamUtil.safeClose(fis);
    }
    return;
}

From source file:org.quartz.impl.jdbcjobstore.oracle.OracleDelegate.java

public int insertJobDetail(Connection conn, JobDetail job) throws IOException, SQLException {

    ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap());
    byte[] data = baos.toByteArray();
    PreparedStatement ps = null;
    ResultSet rs = null;//from  ww  w .  ja  v a 2s .co m

    try {
        ps = conn.prepareStatement(rtp(INSERT_JOB_DETAIL));
        ps.setString(1, job.getName());
        ps.setString(2, job.getGroup());
        ps.setString(3, job.getDescription());
        ps.setString(4, job.getJobClass().getName());
        setBoolean(ps, 5, job.isDurable());
        setBoolean(ps, 6, job.isVolatile());
        setBoolean(ps, 7, job.isStateful());
        setBoolean(ps, 8, job.requestsRecovery());

        ps.setBinaryStream(9, null, 0);
        ps.executeUpdate();
        ps.close();

        ps = conn.prepareStatement(rtp(UPDATE_ORACLE_JOB_DETAIL_EMPTY_BLOB));
        ps.setString(1, job.getName());
        ps.setString(2, job.getGroup());
        ps.executeUpdate();
        ps.close();

        ps = conn.prepareStatement(rtp(SELECT_ORACLE_JOB_DETAIL_BLOB));
        ps.setString(1, job.getName());
        ps.setString(2, job.getGroup());

        rs = ps.executeQuery();

        int res = 0;

        Blob dbBlob = null;
        if (rs.next()) {
            dbBlob = writeDataToBlob(rs, 1, data);
        } else {
            return res;
        }

        rs.close();
        ps.close();

        ps = conn.prepareStatement(rtp(UPDATE_ORACLE_JOB_DETAIL_BLOB));
        ps.setBlob(1, dbBlob);
        ps.setString(2, job.getName());
        ps.setString(3, job.getGroup());

        res = ps.executeUpdate();

        if (res > 0) {
            String[] jobListeners = job.getJobListenerNames();
            for (int i = 0; jobListeners != null && i < jobListeners.length; i++) {
                insertJobListener(conn, job, jobListeners[i]);
            }
        }

        return res;
    } finally {
        closeResultSet(rs);
        closeStatement(ps);
    }

}

From source file:org.fosstrak.epcis.repository.query.QuerySubscription.java

/**
 * Updates the subscription in the database. This is required in order to
 * correctly re-initialize the subscriptions, especially the
 * lastTimeExecuted field, after a context restart.
 * <p>//from www.j  a  v  a2s. c  o  m
 * TODO: This is a back-end method: move this method to the
 * QueryOperationsBackend and delegate to it (thus we would need a reference
 * to the QueryOperationsBackend in this class).
 * 
 * @param lastTimeExecuted
 *            The new lastTimeExecuted.
 */
private void updateSubscription(final Calendar lastTimeExecuted) {
    String jndiName = getProperties().getProperty("jndi.datasource.name", "java:comp/env/jdbc/EPCISDB");
    try {
        // open a database connection
        Context ctx = new InitialContext();
        DataSource db = (DataSource) ctx.lookup(jndiName);
        Connection dbconnection = db.getConnection();

        // update the subscription in the database
        String update = "UPDATE subscription SET lastexecuted=(?), params=(?)" + " WHERE subscriptionid=(?);";
        PreparedStatement stmt = dbconnection.prepareStatement(update);
        LOG.debug("SQL: " + update);
        Timestamp ts = new Timestamp(lastTimeExecuted.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(1, time);
        LOG.debug("       query param 1: " + time);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");
        stmt.setString(3, subscriptionID);
        LOG.debug("       query param 3: " + subscriptionID);
        stmt.executeUpdate();
        dbconnection.commit();

        // close the database connection
        dbconnection.close();
    } catch (SQLException e) {
        String msg = "An SQL error occurred while updating the subscriptions in the database.";
        LOG.error(msg, e);
    } catch (IOException e) {
        String msg = "Unable to update the subscription in the database: " + e.getMessage();
        LOG.error(msg, e);
    } catch (NamingException e) {
        String msg = "Unable to find JNDI data source with name " + jndiName;
        LOG.error(msg, e);
    }
}

From source file:org.accada.epcis.repository.query.QuerySubscription.java

/**
 * Updates the subscription in the database. This is required in order to
 * correctly re-initialize the subscriptions, especially the
 * lastTimeExecuted field, after a context restart.
 * <p>//from  w w w .j  a v a  2  s . c o m
 * TODO: This is a back-end method: move this method to the
 * QueryOperationsBackend and delegate to it (thus we would need a reference
 * to the QueryOperationsBackend in this class).
 * 
 * @param lastTimeExecuted
 *            The new lastTimeExecuted.
 */
private void updateSubscription(final GregorianCalendar lastTimeExecuted) {
    String jndiName = getProperties().getProperty("jndi.datasource.name", "java:comp/env/jdbc/EPCISDB");
    try {
        // open a database connection
        Context ctx = new InitialContext();
        DataSource db = (DataSource) ctx.lookup(jndiName);
        Connection dbconnection = db.getConnection();

        // update the subscription in the database
        String update = "UPDATE subscription SET lastexecuted=(?), params=(?)" + " WHERE subscriptionid=(?);";
        PreparedStatement stmt = dbconnection.prepareStatement(update);
        LOG.debug("SQL: " + update);
        Timestamp ts = new Timestamp(lastTimeExecuted.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(1, time);
        LOG.debug("       query param 1: " + time);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");
        stmt.setString(3, subscriptionID);
        LOG.debug("       query param 3: " + subscriptionID);
        stmt.executeUpdate();

        // close the database connection
        dbconnection.close();
    } catch (SQLException e) {
        String msg = "An SQL error occurred while updating the subscriptions in the database.";
        LOG.error(msg, e);
    } catch (IOException e) {
        String msg = "Unable to update the subscription in the database: " + e.getMessage();
        LOG.error(msg, e);
    } catch (NamingException e) {
        String msg = "Unable to find JNDI data source with name " + jndiName;
        LOG.error(msg, e);
    }
}

From source file:org.sakaiproject.content.impl.serialize.impl.conversion.Type1BlobCollectionConversionHandler.java

public boolean convertSource(String id, Object source, PreparedStatement updateRecord) throws SQLException {

    String xml = (String) source;

    SAXSerializableCollectionAccess sax = new SAXSerializableCollectionAccess();
    SAXSerializableCollectionAccess sax2 = new SAXSerializableCollectionAccess();
    try {/* w ww .jav  a 2 s . c  o  m*/
        sax.parse(xml);
    } catch (Exception e1) {
        log.warn("Failed to parse " + id + "[" + xml + "]", e1);
        return false;
    }

    Type1BaseContentCollectionSerializer t1b = new Type1BaseContentCollectionSerializer();
    t1b.setTimeService(new ConversionTimeService());
    try {
        byte[] result = t1b.serialize(sax);
        t1b.parse(sax2, result);
        sax.check(sax2);

        if (result == null) {
            System.out.println("convertSource(" + id + ") result is NULL");
            ;
        } else {
            //System.out.println("convertSource(" + id + ") result.length == " + result.length + "\n" + new String(result));
            InputStream stream = new ByteArrayInputStream(result);
            updateRecord.setBinaryStream(1, stream, result.length);
            //updateRecord.setBytes(1, result);

            updateRecord.setString(2, id);
            //System.out.println("\n\nconvertSource(" + id + ") result.length == " + result.length + " returning true");

            return true;
        }

    } catch (Exception e) {
        log.warn("Failed to process record " + id, e);
    }
    return false;

}

From source file:org.apache.oozie.tools.OozieDBCLI.java

private void convertClobToBlobinDerby(Connection conn, String startingVersion) throws Exception {
    if (conn == null) {
        return;/* www  .j av a  2s .  c  o  m*/
    }
    System.out.println("Converting clob columns to blob for all tables");
    Statement statement = conn.createStatement();
    for (Map.Entry<String, List<String>> tableClobColumnMap : getTableClobColumnMap().entrySet()) {
        String tableName = tableClobColumnMap.getKey();
        List<String> columnNames = tableClobColumnMap.getValue();
        for (String column : columnNames) {
            statement.executeUpdate(getAddColumnQuery(tableName, TEMP_COLUMN_PREFIX + column, "blob"));
        }
        ResultSet rs = statement.executeQuery(getSelectQuery(tableName, columnNames));
        while (rs.next()) {
            for (String column : columnNames) {
                if (startingVersion.equals(DB_VERSION_PRE_4_0) && tableName.equals("COORD_ACTIONS")
                        && column.equals("push_missing_dependencies")) {
                    // The push_missing_depdencies column was added in DB_VERSION_FOR_4_0 as a CLOB and we're going to convert
                    // it to BLOB in DB_VERSION_FOR_5_0.  However, if Oozie 5 did the upgrade from DB_VERSION_PRE_4_0 to
                    // DB_VERSION_FOR_4_0 (and is now doing it for DB_VERSION_FOR_5_0) push_missing_depdencies will already be a
                    // BLOB because Oozie 5 created the column instead of Oozie 4; and the update query below will fail.
                    continue;
                }
                Clob confClob = rs.getClob(column);
                if (confClob == null) {
                    continue;
                }
                PreparedStatement ps = conn.prepareStatement(
                        "update " + tableName + " set " + TEMP_COLUMN_PREFIX + column + "=? where id = ?");
                byte[] data = IOUtils.toByteArray(confClob.getCharacterStream(), "UTF-8");
                ps.setBinaryStream(1, new ByteArrayInputStream(data), data.length);
                ps.setString(2, rs.getString(1));
                ps.executeUpdate();
                ps.close();
            }
        }
        rs.close();
        for (String column : columnNames) {
            statement.executeUpdate(getDropColumnQuery(tableName, column));
            statement.executeUpdate(
                    "RENAME COLUMN " + tableName + "." + TEMP_COLUMN_PREFIX + column + " TO " + column);
        }
    }
    statement.close();
    System.out.println("DONE");
}