对Blob对象的处理


【对Blob对象的处理】//保存图片
public boolean savePhoto(String rid,String idcard){
Connection conn=null;
PreparedStatement pstmt=null;
FileInputStream file=null;
Statement stmt=null;
ResultSet rs=null;
InputStream in=null;
FileOutputStream out=null;
try {
//基本的jdbc操作
//Class.forName("oracle.jdbc.driver.OracleDriver");
//conn=DriverManager.getConnection("jdbc:oracle:thin:@192.168.3.245:1521:orcl", "cdc", "111111");

//从hibernate那获得connection
Session session = this.getSession();
conn =session.connection();

conn.setAutoCommit(false);
//if(rid == null || rid.equals("")){
//pstmt=conn.prepareStatement("insert into t_a_resident_archives(rid,idcard,photo) values(cdc_seq.NEXTVAL,?,?)");
//pstmt.setString(1, idcard);
//file=new FileInputStream("f:\\3.jpg");
//System.out.println(file.available());
//pstmt.setBlob(2, file);
//}else{
pstmt=conn.prepareStatement("update t_a_resident_archives set photo=? where rid=?");
pstmt.setString(2, rid);
file=new FileInputStream("f:\\3.jpg");
System.out.println(file.available());
pstmt.setBlob(1, file);
//}
pstmt.executeUpdate();
conn.commit();

//读文件
stmt=conn.createStatement();
String sql="select photo from t_a_resident_archives where rid=" + rid;
rs=stmt.executeQuery(sql);
byte[] buffer=new byte[1024];
Blob blob=null;
while(rs.next()){
blob=rs.getBlob(1);
}
in=blob.getBinaryStream();
//存放文件的路径
out=new FileOutputStream("D:\\888.jpg");
int number=in.read(buffer);
//把读取的数据放到字节数组,并写到文件中
while(number!=-1){
out.write(buffer,0,number);
number=in.read(buffer);
}

rs.close();
stmt.close();
file.close();
in.close();
out.close();
conn.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;

}

    推荐阅读