以customers表为例
代码中Customer类的构造查看:针对单个表进行通用的查询操作_qq_46053741的博客-CSDN博客
代码中jdbcConnection类的构造查看:封装数据库的连接关闭操作_qq_46053741的博客-CSDN博客
public class BlobTest {
@Test
public void testQuery(){
//1、获取连接
Connection conn=null;
PreparedStatement ps=null;
InputStream is=null;
FileOutputStream fos=null;
ResultSet rs=null;
try {
conn = jdbcConnection.connection();
//2、创建sql语句,实例化preparedStatement对象
String sql="select id,name,email,birth,photo from customers where id=?";
ps = conn.prepareStatement(sql);
//3、填充占位符
ps.setInt(1,16);
//4、执行,获取结果集
rs=ps.executeQuery();
if(rs.next()){
int id=rs.getInt("id");
String name=rs.getString("name");
String email=rs.getString("email");
Date birth=rs.getDate("birth");
//将Blob类型的字段下载下来,以文件的方式保存在本地
Blob photo=rs.getBlob("photo");
is=photo.getBinaryStream();
fos=new FileOutputStream("月光宝盒.jpg");
byte[] buffer=new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
jdbcConnection.CloseResource(conn, ps,rs);
try {
if(is!=null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos!=null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}