如何在java中将Blob转换为字符串和将字符串转换为Blob [英] How to convert Blob to String and String to Blob in java

查看:257
本文介绍了如何在java中将Blob转换为字符串和将字符串转换为Blob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用

Blob blob = rs.getBlob(cloumnName[i]);
byte[] bdata = blob.getBytes(1, (int) blob.length());
String s = new String(bdata);

它工作正常,但是当我要将 String 转换为 Blob 并尝试插入数据库时​​,没有插入数据库.我使用以下代码将 String 转换为 Blob:

It is working fine but when I'm going to convert String to Blob and trying to insert into database then nothing inserting into database. I've used below code for converting String to Blob:

String value = (s);
byte[] buff = value.getBytes();
Blob blob = new SerialBlob(buff);

谁能帮我在 Java 中将 Blob 转换为 String 并将 String 转换为 Blob?

Can anyone help me about to converting of Blob to String and String to Blob in Java?

推荐答案

试试这个(a2是BLOB col)

try this (a2 is BLOB col)

PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where id=1");
Blob blob = conn.createBlob();
blob.setBytes(1, str.getBytes());
ps1.setBlob(1, blob);
ps1.executeUpdate();

即使没有BLOB也可以工作,驱动程序会自动转换类型:

it may work even without BLOB, driver will transform types automatically:

   ps1.setBytes(1, str.getBytes);
   ps1.setString(1, str);

此外,如果您使用文本,CLOB 似乎是一种更自然的 col 类型

Besides if you work with text CLOB seems to be a more natural col type

这篇关于如何在java中将Blob转换为字符串和将字符串转换为Blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆