- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert BLOB to Byte Array in java?
You can contents of a blob into a byte array using the getBytes() method.
Example
import java.awt.Image; import java.awt.image.BufferedImage; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Arrays; public class BlobToByteArray { public static void main(String[] args) throws Exception { Image image = new BufferedImage(300,400, BufferedImage.TYPE_INT_RGB); String JDBC_DRIVER = "com.mysql.jdbc.Driver"; String DB_URL = "jdbc:mysql://localhost/mydb"; String USER = "root"; String PASS = "password"; Connection conn = null; Statement stmt = null; Class.forName("com.mysql.jdbc.Driver"); System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); System.out.println("getting blob......."); stmt = conn.createStatement(); String sql = "SELECT * FROM sample"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { Blob blob = rs.getBlob("image"); byte [] bytes = blob.getBytes(1l, (int)blob.length()); for(int i=0; i<bytes.length;i++) { System.out.println(Arrays.toString(bytes)); } } } }
Output
Connecting to a selected database... Connected database successfully... getting blob....... [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
Advertisements