如何将 BLOB 转换为 Java 中的字节数组?
您可以使用 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://127.0.0.1/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]
广告