图例分析
关键代码
@Test
public void testBlob() {
retrieveSavePhoto("image.jpg",30);
}
public static void retrieveSavePhoto(String fileName, int id) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
InputStream is = null;
FileOutputStream fos = null;
String sql = "select photo from photo WHERE id=?";//第一个photo是字段名,第二个photo是表名
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
//设置第1个人传入参数id
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob(1);
//得到blob的二进制输入流
is = blob.getBinaryStream();
//把输入流转成输出流
fos = new FileOutputStream(fileName);
//造一个桶
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer))!=-1) {//把输入流读取到buffer里面去,并且赋值给len,并且确保len不等于-1
//fos是输出流
fos.write(null);
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}