gpt4 book ai didi

java - 如何在java中将Blob转换为字符串和字符串转换为Blob

转载 作者:IT老高 更新时间:2023-10-28 20:42:10 42 4
gpt4 key购买 nike

我正在尝试使用

从 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

最佳答案

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

关于java - 如何在java中将Blob转换为字符串和字符串转换为Blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17400497/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com