`
liucyno1
  • 浏览: 11170 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

大数据类型Blob的写

    博客分类:
  • JDBC
阅读更多
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class TestBlob {
public static void main(String[]args){
Connection con =null;
PreparedStatement ps=null;
ResultSet rs = null;
int id=1;
String filename="/home/tarena/day1.zip";
Blob b=null;
try{
con=jdbcUtil.getConnection();
con.setAutoCommit(false);
/*
create table t_blob(
id number(12) primary key,
filename varchar2(55) not null,
fileContant Blob);
*/
String sql ="insert into t_blob values(?,?,empty_blob())";
ps=con.prepareStatement(sql);
ps.setInt(1,id);
ps.setString(2,filename);
ps.executeUpdate();
con.commit();
/*委托数据库,来获得这个Blob对象。
  将空的blob字段值读回来,就获得了一个空的Blob对象。
*/
sql= "select fileContant from t_blob "+
"where id=? for update";//加上update的意思是,在我提交以前,我上锁了。
jdbcUtil.release(ps);
ps=con.prepareStatement(sql);
ps.setInt(1, id);
rs=ps.executeQuery();
if(rs.next()){
b=rs.getBlob(1);
}
/*将文件中的内容 导入到Blob对象中。*/
InputStream in = new FileInputStream(filename);
OutputStream out =b.setBinaryStream(0);
byte[]content = new byte[in.available()];
in.read(content);
out.write(content);
System.out.println(content.length);
in.close();
out.close();
/*将Blob对象更新到数据库中去。
*/
sql="update t_blob set "+
"fileContant=? where id=?";
jdbcUtil.release(rs,ps,null);
ps=con.prepareStatement(sql);
ps.setBlob(1, b);
ps.setInt(2, id);
ps.executeUpdate();
con.commit();
}catch(Exception e){
e.printStackTrace();
try{}catch(Exception el){
el.printStackTrace();
}
}finally{
jdbcUtil.release(null, ps, con);
}

}
}
分享到:
评论
1 楼 wangqiangcattsoft 2009-09-22  
为啥要先添加个空的,再update啊,直接insert blob不行吗

相关推荐

Global site tag (gtag.js) - Google Analytics