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) { } } 

 


__EOF__

本文作者皮军旗
本文链接https://www.cnblogs.com/pijunqi/p/14131522.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   皮军旗  阅读(1458)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示