java将String字符串存入oracle的Blob字段中


Blob内存放的是字节数组,需使用String的getBytes获得该字符串的字节数组(注意字符集编码),然后存入Blob。

Oracle的Blob字段比较特殊,他比long字段的性能要好很多,可以用来保存例如图片之类的二进制数据。写入Blob字段和写入其它类型字段的方式非常不同,不能直接像插入其他普通类型数据一样插入Blob字段数据,因为Blob相当于一个大文件块,里面有游标cursor,你必须使用cursor对Blob进行操作,因而你在写入Blob之前,必须获得cursor。

具体操作步骤是,先插入一个empty的Blob,这将创建一个Blob的cursor,然后你再把这个empty的Blob的cursor用select查询出来,这样通过两步操作,你就获得了Blob的cursor,可以真正地写入Blob数据了。

public static void instertStringIntoBlob(String str) {
        try {
            //获得字符串的字节数组
            byte[] value = null;
            value = str.getBytes("ASCII);
       //blobValue = new SerialBlob(bytes); BLOB类型
//数据库连接 Class.forName("oracle.jdbc.driver.OracleDriver"); String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; String username = "scott"; String password = "scott"; Connection con = DriverManager.getConnection(url, username, password); con.setAutoCommit(false); //插入空Blob,创建cursor String sql1 = "insert into test(id,content) values('999',empty_blob())"; Statement statement = con.createStatement(); statement.execute(sql1); //select获得cursor,并写入数据 String sql2 = "select content from test where id=? for update";
       con.setString(1, id); PreparedStatement stmt
= con.prepareStatement(sql2); ResultSet rs = stmt.executeQuery(); OutputStream outStream = null; if (rs.next()) { BLOB blob = (BLOB) rs.getBlob(1); outStream = blob.getBinaryOutputStream(); outStream.write(value, 0, value.length); } outStream.flush(); outStream.close(); con.commit(); con.close(); } catch (Exception e) { } } 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM