如何在java中将Blob转换为String和String转换为Blob

时间:2013-07-01 08:48:54

标签: java jdbc 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:

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

有人可以帮助我在Java中将Blob转换为StringString转换为Blob吗?

6 个答案:

答案 0 :(得分:7)

试试这个(a2是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也可以工作,驱动程序会自动转换类型:

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

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

答案 1 :(得分:2)

使用此命令将String转换为Blob。其中connection是与db对象的连接。

    String strContent = s;
    byte[] byteConent = strContent.getBytes();
    Blob blob = connection.createBlob();//Where connection is the connection to db object. 
    blob.setBytes(1, byteContent);

答案 2 :(得分:0)

你如何设置blob到DB?  你应该这样做:

 //imagine u have a a prepared statement like:
 PreparedStatement ps = conn.prepareStatement("INSERT INTO table VALUES (?)");
 String blobString= "This is the string u want to convert to Blob";
oracle.sql.BLOB myBlob = oracle.sql.BLOB.createTemporary(conn, false,oracle.sql.BLOB.DURATION_SESSION);
 byte[] buff = blobString.getBytes();
 myBlob.putBytes(1,buff);
 ps.setBlob(1, myBlob);
 ps.executeUpdate();

答案 3 :(得分:0)

要在Java中将Blob转换为String,

byte[] bytes = baos.toByteArray();//Convert into Byte array
String blobString = new String(bytes);//Convert Byte Array into String

答案 4 :(得分:0)

这是我的解决方案,它总是对我有用

StringBuffer buf = new StringBuffer();
String temp;
BufferedReader bufReader = new BufferedReader(new InputStreamReader(myBlob.getBinaryStream()));
    while ((temp=bufReader.readLine())!=null) {
        bufappend(temp);
    }

答案 5 :(得分:0)

这是我的解决方案

从数据库中检索 blob 列并将其传递给以下方法。

 public static String blobToString(BLOB blob) throws Exception {

        byte[] data = new byte[(int) blob.length()];
        BufferedInputStream instream = null;
        try {
        instream = new BufferedInputStream(blob.getBinaryStream());
        instream.read(data);
        } catch (Exception ex) {
        throw new Exception(ex.getMessage());
        } finally {
        instream.close();
        }
        
        int chunk = 65536;
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        GZIPInputStream gis = new GZIPInputStream(bis);

         int length = 0;
        byte[] buffer = new byte[chunk];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((length = gis.read(buffer, 0, chunk)) != -1) {
        bos.write(buffer, 0, length);
        }

        gis.close();
        bis.close();
        bos.close();
        
        String str = bos.toString();
        System.out.println(str);
        return str;

    }