添加blob类型的数据
public void testInsert() throws Exception {
Connection conn = JDBCutils.getConnection();
String sql="insert into testblob (photo) values (?)";
PreparedStatement ps = conn.prepareStatement(sql);
FileInputStream is = new FileInputStream(new File("D:\\JDBC学习\\jdbc_01\\src\\tt.jpg"));
ps.setObject(1,is);
ps.execute();
JDBCutils.closeResource(ps,conn);
is.close();
}
删除、修改等操作与插入操作相似
从数据库中下载blob类型数据
public void testQuery() {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
InputStream is =null;
FileOutputStream fos=null;
try {
conn = JDBCutils.getConnection();
String sql="select photo from testblob";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
if(rs.next()){
Blob photo = rs.getBlob("photo");
is = photo.getBinaryStream();
fos=new FileOutputStream("t1.jpg");
byte[] bytes=new byte[1024];
int len=0;
while ((len=is.read(bytes))!=-1){
fos.write(bytes,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(is!=null){
is.close();
}
if(fos!=null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
JDBCutils.closeResource(ps,conn,rs);
}
|