25

我正在尝试通过使用从 BLOB 数据类型中获取字符串

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

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

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

任何人都可以帮助我在 Java中转换BlobtoStringStringto吗?Blob

4

6 回答 6

8

试试这个(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 类型

于 2013-07-01T09:06:45.117 回答
2

使用它将字符串转换为 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);
于 2013-07-01T08:58:26.027 回答
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();
于 2013-07-01T08:53:51.307 回答
0

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

StringBuffer buf = new StringBuffer();
String temp;
BufferedReader bufReader = new BufferedReader(new InputStreamReader(myBlob.getBinaryStream()));
    while ((temp=bufReader.readLine())!=null) {
        bufappend(temp);
    }
于 2021-01-03T16:33:54.377 回答
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;

    }
于 2021-05-31T13:28:47.550 回答
0

在 Java 中将 Blob 转换为字符串:

byte[] bytes = baos.toByteArray();//Convert into Byte array
String blobString = new String(bytes);//Convert Byte Array into String
于 2019-03-15T05:29:20.173 回答