JDBC对Oracle读写BLOB类型,大对象数据,二进制数据的一些心得

来源:互联网 发布:计算机程序员前景 编辑:程序博客网 时间:2024/05/21 11:10
上周接到一个需求,需要用到对Oracle数据库BLOB类型进行读写操作,BLOB里主要存图片文件。本来想找个DAO框架用用,但是感觉好久没用JDBC写了,就用了JDBC然而平时框架用久了不会遇到也不会注意的问题在JDBC上接连出现。
      
从数据库上读取图片对象到本地文件夹里还比较简单:
                        //建立数据库连接
                           con = DBUtil.getConnection();
PreparedStatement stmt = con.prepareStatement(sql1);
ResultSet rs = stmt.executeQuery(); 
                        
File file = new File(path1 + File.separator       //path1 是路径 和sql1我都写在properties里
+ rs.getInt("attch_id") + "-"    //图片ID
+ rs.getString("file_name"));   //图片名称     整体是一个图片放至在本地硬盘的位置
                        //下面3个流最好要定义在方法前面 例如InputStream fi =null 下面再调用fi = rs.getBinaryStream("file_content");
                        //这样会提高效率,我为了写日志方便就写在这里
                        
InputStream fi = rs.getBinaryStream("file_content");    //file_content是BLOB类型字段存的是大数据对象
        FileOutputStream fo = new FileOutputStream(file);                            
        BufferedOutputStream bo = new BufferedOutputStream(fo); 
                        
byte[] buff = new byte[2048];
int a = 0;
while ((a = fi.read(buff)) > 0) {
fo.flush();//flush很重要
 bo.flush(); 
bo.write(buff);   //把文件写入本地硬盘
}
                        
把本地的文件转成二进制写进BLOB,发现每个数据库的方式都不一样,本来尝试用和读取数据对应的方法来写入数据库后来发现接连报错
oracle.jdbc.driver.T4CPreparedStatement.setBlob(ILjava/io/InputStream;) ,听说这种方法在MySql上是可以用的 Oracle写入BLOB需要用特别的方法,如下是对BLOB对应的语句
    Statement st = con.createStatement();
    //插入一个空对象empty_blob()
    st.executeUpdate("insert into TESTBLOB (ID, NAME, BLOBATTR) values (1, "thename", empty_blob())");
    //锁定数据行进行更新,注意“for update”语句
    ResultSet rs = st.executeQuery("select BLOBATTR from TESTBLOB where ID=1 for update");
    if (rs.next())
    {
        //得到java.sql.Blob对象后强制转换为oracle.sql.BLOB
        oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("BLOBATTR");
        OutputStream outStream = blob.getBinaryOutputStream();
        //data是传入的byte数组,定义:byte[] data
        outStream.write(data, 0, data.length);
    }
    本来想用上面的方法,但是感觉这个要对数据库进行2句语句的操作很不方便,后来自己又想了其他种方法,直接运用二进制进行读写,代码如下:
               
Connection con = null;
PreparedStatement stmt = null;
FileInputStream fis = null;
BufferedInputStream bi = null;
InputStream is = null; 
                Image i = new Image();

                stmt = con.prepareStatement("update tf_cms_attchment set file_size=?,file_content=? where ATTCH_ID=?");
fis = new FileInputStream(f2);
bi = new BufferedInputStream(fis);
byte[] buf = new byte[(int) f2.length()];
fis.read(buf);// 输入流中读取一个图片数据
 
stmt.setString(1, i.getFileSize());
stmt.setBytes(2, buf);
stmt.setInt(3, i.getAttchId());
                stmt.executeUpdate();
stmt.close();
OVER!!!!!!!!!
原创粉丝点击