oracle:图象,从Oracle数据库检索图像的示例

借助PreparedStatement, 我们可以检索图像并将其存储在数据库中。

PreparedStatement的getBlob()方法用于获取二进制信息, 它返回Blob的实例。在blob对象上调用getBytes()方法之后, 我们可以获得可以写入图像文件的二进制信息数组。

PreparedStatement的getBlob()方法的签名

public Blob getBlob()throws SQLException

Blob接口的getBytes()方法的签名

public byte[] getBytes(long pos, int length)throws SQLException

我们假设图像存储在imgtable中。

CREATE TABLE "IMGTABLE"

("NAME" VARCHAR2(4000), "PHOTO" BLOB

)

/

现在, 让我们编写代码以从数据库检索图像并将其写入目录, 以便可以显示它。

在AWT中, 可以通过Toolkit类显示它。在servlet, jsp或html中, 可以通过img标签显示它。

import java.sql.*;

import java.io.*;

public class RetrieveImage {

public static void main(String[] args) {

try{

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");

PreparedStatement ps=con.prepareStatement("select * from imgtable");

ResultSet rs=ps.executeQuery();

if(rs.next()){//now on 1st row

Blob b=rs.getBlob(2);//2 means 2nd column data

byte barr[]=b.getBytes(1, (int)b.length());//1 means first image

FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");

fout.write(barr);

fout.close();

}//end of if

System.out.println("ok");

con.close();

}catch (Exception e) {e.printStackTrace();}

}

}

现在, 如果你看到d驱动器, 就会创建sonoo.jpg图像。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值