To convert a byte array into a 'Blob' (binary large object) object in Java, you can use the 'ByteArrayInputStream' class of the 'java.io' library and the 'Blob' interface of the java.sql library. The 'Blob' interface represents a large binary data object that can be stored in a database or other data source.
Here is an example of how to convert a byte array to a 'Blob' object using the 'ByteArrayInputStream' class:
ferer to:lautturi.comimport java.io.ByteArrayInputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class Main { public static void main(String[] args) { byte[] bytes = // Array de bytes aqui... try (Connection conexao = // Connection to the database here... PreparedStatement statement = conexao.prepareStatement("INSERT INTO tabela (coluna_blob) VALUES (?)")) { // Converts the array of bytes into a Blob object Blob blob = conexao.createBlob(); try (ByteArrayInputStream stream = new ByteArrayInputStream(bytes)) { blob.setBinaryStream(1).use(out -> out.write(bytes)); } // Sets the Blob object as the sql query parameter statement.setBlob(1, blob); // Runs the query statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } }
This code creates a 'Blob' object from a byte array using the 'createBlob' method of the 'Connection' interface and writes it to a 'ByteArrayInputStream'. It then sets the 'Blob' object as a parameter of a SQL query using the 'setBlob' method of the 'PreparedStatement' class and executes the query to insert the 'Blob' object into a database table.