您的位置:首页 > 数据库

通过JDBC和Hibernate对Clob和Blob的操作

2012-06-06 08:51 513 查看
通过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 = inp
4000
utStream.read();

        }

        return outStream.toByteArray();

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息