Blob类型数据存取
@Test
public void insertPhoto() {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JDBCUtils.getConnection();
String sql="insert into fruit(id,photo)values(?,?);";
pstmt = conn.prepareStatement(sql);
pstmt.setObject(1,5);
FileInputStream is=new FileInputStream(new File("D:\\Users\\Desktop\\study\\图片\\photo.png"));
pstmt.setObject(2,is);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResoure(conn,pstmt);
}
}
@Test
public void loadPhoto(){
Connection conn = null;
PreparedStatement pstmt = null;
InputStream is=null;
FileOutputStream fos=null;
ResultSet rs=null;
try {
conn = JDBCUtils.getConnection();
String sql="select * from fruit where id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setObject(1,5);
rs =pstmt.executeQuery();
while (rs.next()){
int id=rs.getInt(1);
Blob photo=rs.getBlob(2);
is= photo.getBinaryStream();
fos =new FileOutputStream("D:\\Users\\Desktop\\study\\图片\\photo1.png");
byte[] buffer=new byte[1024];
int len;
while ((len=is.read(buffer))!= -1){
fos.write(buffer,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
JDBCUtils.closeResoure(conn,pstmt,rs);
}
}