将图片存入Oracle数据库
public int writeBlob(String path,String id) throws SQLException, IOException{
Connection conn = null;
PreparedStatement ps =null;
conn = getConnetion();
int result = 0;
String sql = "insert into man(id,picture) values(?,?)";
conn = getConnetion();
try {
ps = conn.prepareStatement(sql);
//1.����Blob
Blob image = conn.createBlob();
//2.��������blob
OutputStream out = image.setBinaryStream(1);
//3.��ȡͼƬ,��д�������
FileInputStream fis = new FileInputStream(path);
byte []buf = new byte[1024];
int len = 0;
while((len=fis.read(buf))!=-1){
out.write(buf, 0, len);
}
ps.setObject(1,id);
ps.setBlob(2,image);
result = ps.executeUpdate();
fis.close();
out.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.print("error close");
}
}
return result;
}
将图片从数据库中取出
//从数据库中获取图片,path是保存路径
//get picture from oracle
public void downPicture(String id, String path){
Connection conn = null;
PreparedStatement ps =null;
ResultSet rs = null;
ResultSetMetaData rsmd = null;
ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
try {
String sql = "Select * from man Where ID = ?";
conn = getConnetion();
ps =conn.prepareStatement(sql);
ps.setObject(1, id);
rs = ps.executeQuery();
Blob blob =null;
while(rs.next()) {
blob = rs.getBlob("picture");
break;
}
InputStream ins = blob.getBinaryStream();
path = path + "jppicture" + id + ".jpg";
File file = new File(path);
if(!file.exists()){
file.createNewFile();
}
OutputStream fos = new FileOutputStream(file);
byte[] b = new byte[1024];
int len = 0;
while((len = ins.read(b))!=-1){
fos.write(b,0,len);
}
fos.close();
ins.close();
}catch (Exception e){
System.out.print("something error");
}finally {
try {
if(rs != null){
rs.close();
}
if(ps != null){
ps.close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
System.out.print("���ݿ�رճ���");
}
}
}