数据库clob的操作

下面介绍数据库中clob(characher large object)(对应于sql server中中的text字段)字段的操作问题:

在插入的时候可以通过函数Hibernate.createClob()将字符串或者流编程clob类型(java.sql.Clob)或者通过以下的这个东东的转换

public class ClobUtil implements Clob{

    private Reader reader;
    private boolean needsReset = false;
    private int length;
    
    public ClobUtil(String str){
        reader = new StringReader(str);
        length = str.length();
    }

    public InputStream getAsciiStream() throws SQLException {
        try {
            if (needsReset) reader.reset();
        }
        catch (IOException ioe) {
            throw new SQLException("could not reset reader");
        }
        needsReset = true;
        return new ReaderInputStream(reader);
    }

    public Reader getCharacterStream() throws SQLException {
        try {
            if (needsReset) reader.reset();
        }
        catch (IOException ioe) {
            throw new SQLException("could not reset reader");
        }
        needsReset = true;
        return reader;
    }

    public String getSubString(long pos, int length) throws SQLException {
        return null;
    }

    public long length() throws SQLException {
        return  length;
    }

    public long position(String searchstr, long start) throws SQLException {
        return 0;
    }

    public long position(Clob searchstr, long start) throws SQLException {
        return 0;
    }

    public OutputStream setAsciiStream(long pos) throws SQLException {
        return null;
    }

    public Writer setCharacterStream(long pos) throws SQLException {
        return null;
    }

    public int setString(long pos, String str) throws SQLException {
        return 0;
    }

    public int setString(long pos, String str, int offset, int len) throws SQLException {
        return 0;
    }

    public void truncate(long len) throws SQLException {
        
    }
}

 
ClobUtil继承自clob,所以可以直接使用。

当从数据库中取出有clob的字段时,也要用流来处理,如下代码可以实现:
        

eric = dao.getEricByID(13);
Reader reader = eric.getName().getCharacterStream();
//name 为clob类型
BufferedReader br = new BufferedReader(reader);
StringBuffer sb = new StringBuffer();
String s = br.readLine();
sb.append(s);
while(s!=null){
      s = br.readLine();
      sb.append(s);
}
System.out.println(sb.toString());

  

如果数据库为oracle,在取出clob字段时采用如下的方法:

//clobtt为clob类型

Writer wr = clobtt.getCharacterOutputStream(); 
wr.write(strtmp); 
wr.flush(); 
wr.close(); 

  

如果数据库为mysql,最好修改如下文件:

my.ini里面的max_allowed_packet ,这个限制了blob文件可存放的最大的容量,默认好像是1m

你可能感兴趣的:(oracle,sql,mysql,Hibernate,SQL Server)