我们如何使用JDBC中的getBinaryStream()方法从表中检索Blob数据类型?
ResultSet接口提供了一种名称getBlob()为从数据库表中检索Blob数据类型的方法。除此之外,它还提供了一个名为getBinaryStream()的方法。
与getBlob()一样,此方法也接受表示列索引的整数(或表示列名称的String值)并检索指定列的值。区别与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