如何在Java中将BLOB转换为字节数组?
您可以使用getBytes()
方法将Blob的内容放入字节数组。
示例
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)); } } } }
输出结果
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]