如何使用 JDBC 中的 getBinaryStream() 方法从表中检索 blob 数据类型?
jdbcjava 8object oriented programmingprogramming更新于 2025/4/27 19:22:17
ResultSet 接口提供名为 getBlob() 的方法来从数据库的表中检索 blob 数据类型。除此之外,它还提供了一个名为 getBinaryStream()
的方法与 getBlob() 一样,此方法也接受表示列索引的整数(或表示列名称的字符串值)并检索指定列的值。不同之处在于,与 getBlob() 方法(返回 Blob 对象)不同,此方法返回一个 InputStream 对象,该对象以未解释的字节形式保存 blob 数据类型的内容。
示例
假设我们在数据库中创建了一个名为 MyTable 的表,其描述如下。
+-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | image | blob | YES | | NULL | | +-------+--------------+------+-----+---------+-------+
此外,我们在其中插入了一个名为 sample_image 的图像。以下程序使用 getString() 和 getBinaryStream() 方法检索 MyTable 的内容。
import java.io.FileOutputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class RetrievingBlob_ByteStream { public static void main(String args[]) throws Exception { //注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //获取连接 String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //创建 Statement 对象 Statement stmt = con.createStatement(); //检索数据 ResultSet rs = stmt.executeQuery("select * from MyTable"); int i = 0; System.out.println("Contents of the table"); while(rs.next()) { System.out.println(rs.getString("Name")); InputStream inputStream = rs.getBinaryStream("image"); byte byteArray[] = new byte[inputStream.available()]; inputStream.read(byteArray); FileOutputStream outPutStream = new FileOutputStream("E:\images\blob_output"+i+".jpg"); outPutStream.write(byteArray); System.out.println("E:\images\blob_output"+i+".jpg"); } } }
输出
Connection established...... Contents of the table sample_image E:\images\blob_output0.jpg