您的位置:首页 > 博客中心 > 数据库 >

Oracle数据库插入二进制字段数据

时间:2022-03-13 23:57

oracle数据库喜欢搞特殊,二进制字段数据不能直接插入,需先再该字段插入oracle函数返回的的初始数据,然后在查询更新该字段。下面以Blob字段类型为例:

1.插入初始数据

  Class.forName("oracle.jdbc.driver.OracleDriver");  
    Connection cn= DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.5:1521:orcl", "qywsbspt", "qywsbspt123999");

  cn.setAutoCommit(false);

  PreparedStatement pst = cn.prepareStatement("insert into t_uploadfile (file_id,file_content) values (?,EMPTY_BLOB())");

  pst.setObject(1,8888);

  pst.excuteUpdate();

2.查询更新该字段

  pst =   cn.prepareStatement("select  file_content  from t_uploadfile  for update where file_id = ? ");

  pst.setObject(1,8888);

  ResultSet rs = pst.excuteQuery();

  BLOB blob = null ; //不是java.sql.Blob,而是oralce.sql.BLOB

  if(rs.next())

    blob = (BLOB)rs.getBlob(1);  //获取该字段

  OutputStream os =blob.getBinaryOutputStream(); //打开操作该字段的流

  InputStream is = ...... //获取要插入的二进制文件的输入流

  int buffer = -1;

  while((buffer = is.read())!=-1){
       os.write(buffer);
      } 

  is.close();

    os.close(); 

  cn.commit();

  rs.close();

  pst.close();

  cn.close();

  

  

热门排行

今日推荐

热门手游