我试图通过使用从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
转换为String
和String
到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类型
使用此命令将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);
你如何设置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();
要在Java中将Blob转换为String:
byte[] bytes = baos.toByteArray();//Convert into Byte array
String blobString = new String(bytes);//Convert Byte Array into String