Example usage for java.sql PreparedStatement setBytes

List of usage examples for java.sql PreparedStatement setBytes

Introduction

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

Prototype

void setBytes(int parameterIndex, byte x[]) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java array of bytes.

Usage

From source file:dao.CarryonRecentAddQuery.java

/**
 * This method is not called by spring.//  www  .  j av a  2 s .c  o  m
 * This method adds an entry into pblob
 * @param conn the connection
 * @param ownerid 
 * @param entryid 
 * @param category 
 * @param btitle 
 * @param mimeType 
 * @param bsize 
 * @param zoom 
 * @param caption 
 * @exception BaseDaoException
 */
public void run(Connection conn, String ownerid, String entryid, int category, String btitle, String mimeType,
        long bsize, int zoom, String caption) throws BaseDaoException {

    byte[] capBytes = { ' ' };
    if (!RegexStrUtil.isNull(caption)) {
        capBytes = caption.getBytes();
    }
    String stmt = "insert into pblob values(?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP(), ?, ?, ?, ?)";
    PreparedStatement s = null;
    try {
        s = conn.prepareStatement(stmt);
        s.setLong(1, 0);
        s.setLong(2, new Long(entryid));
        s.setLong(3, new Long(ownerid));
        s.setInt(4, new Integer(category));
        s.setString(5, mimeType);
        s.setString(6, btitle);
        s.setLong(7, bsize);
        s.setInt(8, new Integer(zoom));
        s.setInt(9, 0);
        s.setBytes(10, capBytes);
        s.executeUpdate();
    } catch (SQLException e) {
        logger.error("Error adding a blob.", e);
        throw new BaseDaoException("Error adding pblob " + stmt, e);
    }
}

From source file:com.cedarsoftware.ncube.NCubeManager.java

/**
 * Update the passed in NCube.  Only SNAPSHOT ncubes can be updated.
 *
 * @param connection JDBC connection//from w  w  w. j  a va  2 s.  c o  m
 * @param ncube      NCube to be updated.
 * @return boolean true on success, false otherwise
 */
public static boolean updateCube(Connection connection, String app, NCube ncube, String version) {
    validate(connection, app, version);
    if (ncube == null) {
        throw new IllegalArgumentException("NCube cannot be null for updating");
    }

    synchronized (cubeList) {
        PreparedStatement stmt = null;
        try {
            stmt = connection.prepareStatement(
                    "UPDATE n_cube SET cube_value_bin=?, update_dt=? WHERE app_cd = ? AND n_cube_nm = ? AND version_no_cd = ? AND status_cd = '"
                            + ReleaseStatus.SNAPSHOT + "'");
            stmt.setBytes(1, new JsonFormatter().format(ncube).getBytes("UTF-8"));
            stmt.setDate(2, new java.sql.Date(System.currentTimeMillis()));
            stmt.setString(3, app);
            stmt.setString(4, ncube.getName());
            stmt.setString(5, version);
            int count = stmt.executeUpdate();
            if (count != 1) {
                throw new IllegalStateException("Only one (1) row should be updated.");
            }
            ncube.setVersion(version);
            return true;
        } catch (IllegalStateException e) {
            throw e;
        } catch (Exception e) {
            String s = "Unable to update NCube: " + ncube.getName() + ", app: " + app + ", version: " + version;
            LOG.error(s, e);
            throw new RuntimeException(s, e);
        } finally {
            jdbcCleanup(stmt);
        }
    }
}

From source file:db.migration.V2017_08_27_14_00__Import_Images_Into_Db.java

@Override
public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
    LOG.info("Importing images into db");
    List<ImageObject> images = jdbcTemplate.query(
            "select `" + FIELD_ID + "`, `" + FIELD_FILE_PATH + "` from `" + TABLE_NAME + "`",
            new ImageObjectRowMapper<>());
    for (ImageObject entry : images) {
        try {//from  www  .  j a v  a 2s  .  c  om
            File file = new File(entry.getFilePath());
            byte[] data = IOUtils.toByteArray(new FileInputStream(file));
            if (data != null) {
                ImageCategory category = getCategory(entry.getFilePath());
                jdbcTemplate.update(connection -> {
                    PreparedStatement ps = connection.prepareStatement(
                            String.format("update `%s` set `%s` = ?, `%s` = ?, `%s` = ? where `%s` = ?",
                                    TABLE_NAME, FIELD_CONTENT_LENGTH, FIELD_CONTENT, FIELD_CATEGORY, FIELD_ID),
                            new String[] { FIELD_CONTENT });
                    ps.setLong(1, 0L + data.length);
                    ps.setBytes(2, data);
                    ps.setString(3, category.name());
                    ps.setLong(4, entry.getId());
                    return ps;
                });
            }
        } catch (Exception e) {
            LOG.error(String.format("Unable to import file %s: %s", entry.getFilePath(), e.getMessage()));
        }
    }
    LOG.info("Done importing images into db");
}

From source file:com.cedarsoftware.ncube.NCubeManager.java

/**
 * Update the test data associated to an NCube
 *
 * @return true if the update succeeds, false otherwise
 *///  www.ja  v a 2 s.  co m
public static boolean updateTestData(Connection connection, String app, String name, String version,
        String testData) {
    validate(connection, app, version);
    validateCubeName(name);

    synchronized (cubeList) {
        PreparedStatement stmt = null;
        try {
            stmt = connection.prepareStatement(
                    "UPDATE n_cube SET test_data_bin=?, update_dt=? WHERE app_cd = ? AND n_cube_nm = ? AND version_no_cd = ? AND status_cd = '"
                            + ReleaseStatus.SNAPSHOT + "'");
            stmt.setBytes(1, testData == null ? null : testData.getBytes("UTF-8"));
            stmt.setDate(2, new java.sql.Date(System.currentTimeMillis()));
            stmt.setString(3, app);
            stmt.setString(4, name);
            stmt.setString(5, version);
            int count = stmt.executeUpdate();
            if (count > 1) {
                throw new IllegalStateException("Only one (1) row's test data should be updated.");
            }
            if (count == 0) {
                throw new IllegalStateException(
                        "No NCube matching app: " + app + ", name: " + name + ", version: " + version);
            }
            return true;
        } catch (IllegalStateException e) {
            throw e;
        } catch (Exception e) {
            String s = "Unable to update test data for NCube: " + name + ", app: " + app + ", version: "
                    + version;
            LOG.error(s, e);
            throw new RuntimeException(s, e);
        } finally {
            jdbcCleanup(stmt);
        }
    }
}

From source file:ccc.cli.NewDBQueries.java

/**
 * Creates migration user./*from w w  w  .  ja  va2  s .  c  om*/
 *
 * @param username The username for the new user.
 * @param email The email for the new user.
 * @param password The password for the new user.
 *
 * @return UUID of the created user.
 */
public UUID insertMigrationUser(final String username, final String email, final String password) {
    final UUID uid = UUID.randomUUID();
    final byte[] hash = Encryption.hash(password, uid.toString());

    PreparedStatement ps = null;

    try {
        // insert user
        ps = _connection.prepareStatement(
                "INSERT INTO users (id, email, username, vn, hash, name) " + "VALUES (?,?,?,?,?,?)");
        ps.setString(1, uid.toString());
        ps.setString(2, email);
        ps.setString(3, username);
        ps.setInt(4, 0);
        ps.setBytes(5, hash);
        ps.setString(6, username);
        ps.executeUpdate();

        final PreparedStatement gs = _connection.prepareStatement("select id from groups where name in "
                + "('ADMINISTRATOR', 'SITE_BUILDER', 'CONTENT_CREATOR')");
        final ResultSet groups = gs.executeQuery();

        // insert permission
        while (groups.next()) {
            ps = _connection.prepareStatement("INSERT INTO user_roles (user_id, group_id) " + "VALUES (?, ?)");
            ps.setString(1, uid.toString());
            ps.setString(2, groups.getString(1));
            ps.executeUpdate();
        }

        groups.close();
        gs.close();

        _connection.commit();
    } catch (final SQLException e) {
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(ps);
    }
    return uid;
}

From source file:dao.ColStreamBlobAddQuery.java

/**
* This method is used to add blobstreams for directory.
* @param conn - the connection/*w w w.  j  a  v  a  2s  .  c o m*/
* @param blob - the blob stream
* @param blobType - the blob type (1 - photos, 2-music, 3-video 4 -
* documents, 5 - archives)
* @param mimeType - the mime type (image/jpeg,
* application/octet-stream)
* @param btitle - the title for this blob
* @param bsize - the size of the blob
* @param zoom - the zoom for the blob (used for displaying for
* image/jpeg)
* @param collabrumid - the collabrumid
* @param loginId - the loginId
* @param caption - caption
* @throws Dao Exception - when an error or exception occurs while
* inserting this blob in DB.
*
 **/
public void run(Connection conn, byte[] blob, int blobtype, String mimetype, String btitle, long bsize,
        int zoom, String collabrumid, String loginid, String caption) throws BaseDaoException {

    // long dt = new java.util.Date().getTime();
    byte[] capBytes = { ' ' };
    if (!RegexStrUtil.isNull(caption)) {
        capBytes = caption.getBytes();
    }

    long dt = System.currentTimeMillis();
    PreparedStatement s = null;
    String stmt = "insert into collblob values(?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP(), ?, ?, ?, ?)";
    try {
        s = conn.prepareStatement(stmt);
        s.setLong(1, 0);
        s.setLong(2, new Long(collabrumid));
        s.setLong(3, new Long(loginid));
        s.setInt(4, new Integer(blobtype));
        s.setString(5, mimetype);
        s.setString(6, btitle);
        //s.setDate(7, new Date(dt));
        s.setBytes(7, blob);
        s.setLong(8, bsize);
        s.setInt(9, new Integer(zoom));
        s.setBytes(10, capBytes);
        s.executeUpdate();
    } catch (Exception e) {
        throw new BaseDaoException("Error adding a blob to collabrum query  stmt " + stmt, e);
    }
}

From source file:ttpserver.UserCreation.java

public void Register(int userid, String password, int role, int keySize, Params params) {

    //Initialize some useful variables
    User owner;/*from  w  w w .  j a va2 s . c  o m*/
    KeyGen key;
    boolean isOwner;
    owner = new User();
    byte[] userCurveParams = null;
    byte[] userG = null;
    byte[] userK = null;
    byte[] userGK = null;
    byte[] userZK = null;

    //Turn password into byte array and create a hash
    byte[] passwordBytes = password.getBytes();
    passwordBytes = hash(passwordBytes);

    //generate the keys for the data owner
    key = new KeyGen(params);
    owner = key.generate();

    byte[] publicKey = owner.getPKBytes();
    byte[] privateKey = owner.getSKBytes();

    userG = params.getgBytes();
    userK = params.getkBytes();
    userGK = params.getg_kBytes();
    userZK = params.getz_kBytes();

    //Old code which can be used to Serialize/Deserialize  
    //Serializer series = new Serializer();         
    //byte[] pairingBytes = series.serialize(params.getPairing());

    //byte[] curveParamsBytes = new byte[10000];  
    //curveParamsBytes = SerializationUtils.serialize(params.getCurveParameters());
    //System.out.println(Arrays.toString(curveParamsBytes));                        // these three not used
    byte[] curveParamsBytes = new byte[5];

    //Store all generated keys to MySQL database  

    //Set up the connection
    Connection connection = null;
    Statement stmt = null;

    try {
        connection = DatabaseManager.getInstance().getConnection();
        stmt = connection.createStatement();
        PreparedStatement pstmt = connection.prepareStatement(
                "INSERT INTO USER_TABLE(userID, password, pairing, g, k, gk, zk,  publicKey, secretKey, role) VALUE(?,?,?,?,?,?,?,?,?,?)");

        //set values            
        pstmt.setInt(1, userid);
        pstmt.setBytes(2, passwordBytes);
        pstmt.setBytes(3, curveParamsBytes);
        pstmt.setBytes(4, userG);
        pstmt.setBytes(5, userK);
        pstmt.setBytes(6, userGK);
        pstmt.setBytes(7, userZK);
        pstmt.setBytes(8, publicKey);
        pstmt.setBytes(9, privateKey);
        pstmt.setInt(10, role);
        pstmt.executeUpdate();

    } catch (Exception ex) {
        //Logger.getLogger(TTPServer.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    }

    finally {
        try {
            connection.close();
        } catch (Exception e1) {
            System.out.println("Exception while closing connection::" + e1.getMessage());
        }
        try {
            stmt.close();
        } catch (Exception e2) {
            System.out.println("Exception while closing statement::" + e2.getMessage());
        }
    }

}

From source file:org.opencms.db.generic.CmsSqlManager.java

/**
 * Sets the designated parameter to the given Java array of bytes.<p>
 * /*from   ww w.jav a2  s.  co m*/
 * The driver converts this to an SQL VARBINARY or LONGVARBINARY (depending on the argument's 
 * size relative to the driver's limits on VARBINARY values) when it sends it to the database. 
 * 
 * @param statement the PreparedStatement where the content is set
 * @param pos the first parameter is 1, the second is 2, ...
 * @param content the parameter value 
 * @throws SQLException if a database access error occurs
 */
public void setBytes(PreparedStatement statement, int pos, byte[] content) throws SQLException {

    if (content.length < 2000) {
        statement.setBytes(pos, content);
    } else {
        statement.setBinaryStream(pos, new ByteArrayInputStream(content), content.length);
    }
}

From source file:dao.DirectoryAddStreamBlobQuery.java

/**
* This method is used to add blobstreams for directory.
* @param conn - the connection//ww  w . jav  a2 s  .  com
* @param blob - the blob stream
* @param blobType - the blob type (1 - photos, 2-music, 3-video 4 - documents, 5 - archives)
* @param mimeType - the mime type (image/jpeg, application/octet-stream)
* @param btitle - the title for this blob
* @param bsize - the size of the blob
* @param zoom - the zoom for the blob (used for displaying for image/jpeg)
* @param directoryId - the directoryId
* @param loginId - the loginId
* @param caption - the caption
* Modified query to accessdate at the end
* @throws Dao Exception - when an error or exception occurs while inserting this blob in DB.
*
 **/

public void run(Connection conn, byte[] blob, int blobType, String mimeType, String btitle, long bsize,
        int zoom, String directoryId, String loginId, String caption) throws BaseDaoException {

    // long dt = new java.util.Date().getTime();
    byte[] capBytes = { ' ' };
    if (!RegexStrUtil.isNull(caption)) {
        capBytes = caption.getBytes();
    }

    long dt = System.currentTimeMillis();
    PreparedStatement s = null;
    String stmt = "insert into dirblob values(?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP(), ?, ?, ?, ?, CURRENT_TIMESTAMP())";
    try {
        s = conn.prepareStatement(stmt);
        s.setLong(1, 0);
        s.setLong(2, new Long(directoryId));
        s.setLong(3, new Long(loginId));
        s.setInt(4, new Integer(blobType));
        s.setString(5, mimeType);
        s.setString(6, btitle);
        // s.setDate(7, new Date(dt));
        s.setBytes(7, blob);
        s.setLong(8, bsize);
        s.setInt(9, new Integer(zoom));
        s.setBytes(10, capBytes);
        s.executeUpdate();
    } catch (Exception e) {
        throw new BaseDaoException("Error adding a blob to directory query  stmt " + stmt, e);
    }
}

From source file:dao.CarryonBlobUpdate.java

/**
* This method is used to add blobstreams for a user. <code>Userpage</code>
* @param blob - the blob stream//from ww  w. j  a  v  a2  s .  c o  m
* @param category - the blob type (1 - photos, 2-music, 3-video 4 - documents, 5 - archives)
* @param mimeType - the mime type (image/jpeg, application/octet-stream)
* @param btitle - the title for this blob
* @param loginId - the loginId
* @param bsize - the size of the blob
* @param zoom - the zoom for the blob (used for displaying for image/jpeg)
* @throws Dao Exception - when an error or exception occurs while inserting this blob in DB.
*
 **/
public void run(Connection conn, byte[] blob, int category, String mimeType, String btitle, String loginId,
        long bsize, int zoom, String caption) throws BaseDaoException {

    byte[] capBytes = { ' ' };
    if (!RegexStrUtil.isNull(caption)) {
        capBytes = caption.getBytes();
    }

    //long dt = System.currentTimeMillis();
    // Connection conn = null;
    String stmt = "insert into carryon values(?, ?, ?, ?, ?, CURRENT_TIMESTAMP(), ?, ?, ?, ?, ?)";
    PreparedStatement s = null;
    try {
        //    conn = dataSource.getConnection();
        s = conn.prepareStatement(stmt);
        s.setLong(1, 0); // entryid
        s.setLong(2, new Long(loginId)); // loginid
        s.setInt(3, new Integer(category)); // category
        s.setString(4, mimeType); // mimetype
        s.setString(5, btitle); // btitle
        // s.setDate(6, new Date(dt));
        // s.setDate(6, CURRENT_TIMESTAMP());
        s.setBytes(6, blob);
        s.setLong(7, bsize);
        s.setInt(8, new Integer(zoom));
        s.setInt(9, 0); // hits
        s.setBytes(10, capBytes); // caption
        s.executeUpdate();
    } catch (SQLException e) {
        logger.error("Error adding a blob.", e);
        throw new BaseDaoException("Error adding a blob " + e.getMessage(), e);
    }
}