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:Main.java

public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);/*from  ww w. j  a v  a2 s . c  om*/

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    String sql = "INSERT INTO mysql_all_table(" + "col_boolean," + "col_byte," + "col_short," + "col_int,"
            + "col_long," + "col_float," + "col_double," + "col_bigdecimal," + "col_string," + "col_date,"
            + "col_time," + "col_timestamp," + "col_asciistream," + "col_binarystream," + "col_blob) "
            + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    PreparedStatement pstmt = connection.prepareStatement(sql);

    pstmt.setBoolean(1, true);
    pstmt.setByte(2, (byte) 123);
    pstmt.setShort(3, (short) 123);
    pstmt.setInt(4, 123);
    pstmt.setLong(5, 123L);
    pstmt.setFloat(6, 1.23F);
    pstmt.setDouble(7, 1.23D);
    pstmt.setBigDecimal(8, new BigDecimal(1.23));
    pstmt.setString(9, "a string");
    pstmt.setDate(10, new java.sql.Date(System.currentTimeMillis()));
    pstmt.setTime(11, new Time(System.currentTimeMillis()));
    pstmt.setTimestamp(12, new Timestamp(System.currentTimeMillis()));

    File file = new File("infilename1");
    FileInputStream is = new FileInputStream(file);
    pstmt.setAsciiStream(13, is, (int) file.length());

    file = new File("infilename2");
    is = new FileInputStream(file);
    pstmt.setBinaryStream(14, is, (int) file.length());

    file = new File("infilename3");
    is = new FileInputStream(file);
    pstmt.setBinaryStream(15, is, (int) file.length());

    pstmt.executeUpdate();
}

From source file:com.trackplus.ddl.DataWriter.java

private static void insertBlobData(Connection con, String line) throws DDLException {
    String sql = "INSERT INTO TBLOB(OBJECTID, BLOBVALUE, TPUUID) VALUES(?,?,?)";
    StringTokenizer st = new StringTokenizer(line, ",");
    Integer objectID = Integer.valueOf(st.nextToken());
    String base64Str = st.nextToken();
    byte[] bytes = Base64.decodeBase64(base64Str);
    String tpuid = null;/*from w w  w.  j  a  v  a 2s  . co  m*/
    if (st.hasMoreTokens()) {
        tpuid = st.nextToken();
    }

    try {
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setInt(1, objectID);
        preparedStatement.setBinaryStream(2, new ByteArrayInputStream(bytes), bytes.length);
        preparedStatement.setString(3, tpuid);
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        throw new DDLException(e.getMessage(), e);
    }
}

From source file:com.cisco.iwe.services.util.EmailMonitor.java

/** This method saves the email contents in the database  **/
public static void saveAttachmentAndText(String from, String subject, byte[] mailAttachment, byte[] MailText,
        String fileType, Date sent, String pdfText) throws Exception {

    Connection conn = null;//  w ww. ja v a2 s.c om
    PreparedStatement stmt = null;
    try {
        String query = EmailParseConstants.saveQuery;
        conn = DataBaseUtil.getDevConnection();
        // DataBaseUtil.getConnection(jndiName+"_"+System.getProperty("cisco.life"));
        conn.setAutoCommit(false);
        stmt = conn.prepareStatement(query);
        stmt.setString(1, from);
        stmt.setString(2, subject);
        stmt.setBinaryStream(3, new ByteArrayInputStream(mailAttachment), mailAttachment.length);
        stmt.setBinaryStream(4, new ByteArrayInputStream(MailText), MailText.length);
        stmt.setString(5, fileType);
        stmt.setTimestamp(6, new Timestamp(sent.getTime()));
        stmt.executeUpdate();
    } finally {
        try {
            if (stmt != null) {
            }
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }

}

From source file:com.UploadAction.java

public String execute() throws Exception {
    try {// www . j a v a 2s.  c o m
        //long maxFileSize = (2 * 1024 * 1024);
        //int maxMemSize = (2 * 1024 * 1024);
        //final String path = "/tmp";
        HttpServletRequest request = ServletActionContext.getRequest();
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                if (fileItem.isFormField()) {
                    //processFormField(fileItem);
                } else {
                    flItem = fileItem;
                }
            }
        }
        HttpSession session = ServletActionContext.getRequest().getSession(false);
        String User = (String) session.getAttribute("username");
        Connection con = Connections.conn();
        PreparedStatement stat = con.prepareStatement("update user set image=? where UserName=?");
        stat.setString(2, User);
        stat.setBinaryStream(1, flItem.getInputStream(), (int) flItem.getSize());
        // stat.setBinaryStream(4, (InputStream) itemPhoto.getInputStream(), (int) itemPhoto.getSize());
        int rows = stat.executeUpdate();
        if (rows > 0) {
            return "success";
        }
    } catch (Exception e) {
    }
    return "success";
}

From source file:mercury.DigitalMediaDAO.java

public final Integer uploadToDigitalMedia(FileItem file) {
    Connection con = null;//from  w ww .  j av  a 2 s . co m
    Integer serial = 0;
    String filename = file.getName();

    if (filename.lastIndexOf('\\') != -1) {
        filename = filename.substring(filename.lastIndexOf('\\') + 1);
    }

    if (filename.lastIndexOf('/') != -1) {
        filename = filename.substring(filename.lastIndexOf('/') + 1);
    }

    try {
        InputStream is = file.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        serial = getNextSerial("digital_media_id_seq");
        if (serial != 0) {
            con = getDataSource().getConnection();
            con.setAutoCommit(false);
            String sql = " INSERT INTO digital_media " + " (id, file, mime_type, file_name) "
                    + " VALUES (?, ?, ?, ?) ";
            PreparedStatement pstm = con.prepareStatement(sql);
            pstm.setInt(1, serial);
            pstm.setBinaryStream(2, bis, (int) file.getSize());
            pstm.setString(3, file.getContentType());
            pstm.setString(4, filename);
            pstm.executeUpdate();
            pstm.close();
            is.close();
            con.commit();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DAOException(e.getMessage());
    } finally {
        closeConnection(con);
    }
    return serial;
}

From source file:de.whs.poodle.repositories.FileRepository.java

public int uploadFile(MultipartFile file) throws IOException {
    InputStream in = file.getInputStream();

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbc.update(con -> {/* www.  ja va  2  s . c  o m*/
        PreparedStatement ps = con.prepareStatement(
                "INSERT INTO uploaded_file(data,mimetype,filename) VALUES(?,?,?)", new String[] { "id" });

        ps.setBinaryStream(1, in, file.getSize());
        ps.setString(2, file.getContentType());
        ps.setString(3, file.getOriginalFilename());
        return ps;
    }, keyHolder);

    return keyHolder.getKey().intValue();
}

From source file:com.wabacus.config.database.type.AbsDatabaseType.java

public void setBlobValue(int iindex, InputStream in, PreparedStatement pstmt) throws SQLException {
    if (in == null) {
        pstmt.setBinaryStream(iindex, null, 0);
    } else {/*from  www  . j  a  va2  s  .  c  om*/
        try {
            pstmt.setBinaryStream(iindex, in, in.available());
        } catch (IOException e) {
            throw new WabacusRuntimeException("??", e);
        }
    }
}

From source file:com.wabacus.config.database.type.AbsDatabaseType.java

public void setBlobValue(int iindex, byte[] value, PreparedStatement pstmt) throws SQLException {
    if (value == null) {
        pstmt.setBinaryStream(iindex, null, 0);
    } else {//w  ww.  jav a2 s  . c o  m
        try {
            ByteArrayInputStream in = Tools.getInputStreamFromBytesArray(value);
            pstmt.setBinaryStream(iindex, in, in.available());
            in.close();
        } catch (IOException e) {
            throw new WabacusRuntimeException("??", e);
        }
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.TestSQLBinaryManager.java

@Test
public void testSQLBinaryManagerDuplicate() throws Exception {
    DocumentModel file = new DocumentModelImpl("/", "myfile", "File");
    file = session.createDocument(file);
    session.save();//from  w  w w  .jav a  2s .  c  o  m

    byte[] bytes = CONTENT.getBytes("UTF-8");

    // pre-create value in table to force collision
    DataSource dataSource = DataSourceHelper.getDataSource(DATASOURCE);
    Connection connection = dataSource.getConnection();
    String sql = String.format("INSERT INTO %s (%s, %s) VALUES (?, ?)", TABLE, SQLBinaryManager.COL_ID,
            SQLBinaryManager.COL_BIN);
    PreparedStatement ps = connection.prepareStatement(sql);
    ps.setString(1, CONTENT_MD5);
    ps.setBinaryStream(2, new ByteArrayInputStream(bytes), bytes.length);
    ps.execute();
    connection.close();

    // don't do collision checks to provoke insert collision
    SQLBinaryManager.disableCheckExisting = true;

    Blob blob = new StringBlob(CONTENT, "application/octet-stream");
    file.setProperty("file", "content", blob);
    session.saveDocument(file);
    session.save();
}

From source file:org.apache.lucene.store.jdbc.index.AbstractJdbcIndexOutput.java

public void close() throws IOException {
    super.close();
    final long length = length();
    doBeforeClose();/*from w  ww  .  j  av a2 s.  c  o m*/
    jdbcDirectory.getJdbcTemplate().update(jdbcDirectory.getTable().sqlInsert(), new PreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setFetchSize(1);
            ps.setString(1, name);
            InputStream is = null;
            try {
                is = openInputStream();
                if (jdbcDirectory.getDialect().useInputStreamToInsertBlob()) {
                    ps.setBinaryStream(2, is, (int) length());
                } else {
                    ps.setBlob(2, new InputStreamBlob(is, length));
                }
                ps.setLong(3, length);
                ps.setBoolean(4, false);
            } catch (IOException e) {
                throw new SQLException(e);
            }
        }
    });
    doAfterClose();
}