本文主要简介通过JDBC和Hibernate对Clob和Blob的操作,插入和读取.
一,JDBC方式:
1,当lob的内容很小的时候,用sta.setString(2, "clob content"); sta.setBytes(3, "blob".getBytes());
2,通过steam的方式写入内容:
InputStream fis1 = new StringBufferInputStream("test");
sta.setAsciiStream(2, fis1, len);
InputStream fis2 = new StringBufferInputStream("test");
sta.setBinaryStream(3, fis2, len);
二,Hibernate方式:
1,把String的内容插入数据库:
lob.setClobdat(Hibernate.createClob("clob"));
lob.setBlobdat(Hibernate.createBlob("blob".getBytes()));
2,通过steam的方式写入内容:
Hibernate.createClob(Reader reader, int length)
Hibernate.createBlob(InputStream stream)
从数据库读取Lob的内容:clob提供了getCharacterStream()返回Reader,blob提供了getBinaryStream()返回InputStream.
public static String readClob(Clob clob) throws SQLException, IOException {
BufferedReader br = new BufferedReader(clob.getCharacterStream());
StringBuffer strbf = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
strbf.append(str);
}
return strbf.toString();
}
public static byte[] readBlob(Blob blob) throws SQLException, IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
InputStream inputStream = blob.getBinaryStream();
int b = inputStream.read();
while (b != -1) {
outStream.write(b);
b = inputStream.read();
}
return outStream.toByteArray();
}