java代码写入clob字段

oracle在使用clob字段的时候一直无法写入数据库,在网上也找了很久,最后找到一种使用jdbc写入数据库的方式记录一下
 


实体类中我定义的是String类型

一:写入

public void updateStr(String newAddStr,String id){
        Connection conn = DBHrlper.getMyConnection();//大家可以使用自己编写的JDBC连接
        String  sql = "UPDATE TABLE SET CONTENT = ? WHERE ID = ? ";
        PreparedStatement ps;
        try {
            ps = conn.prepareStatement(sql);
            Reader clobReader = new StringReader(newAddStr); // 将 text转成流形式
            ps.setCharacterStream(1, clobReader, newAddStr.length());
            ps.setString(2, id);
            ps.executeUpdate();// 执行SQL
            ps.close();
            conn.close();
        }catch (SQLException e) {
            e.printStackTrace();
        }
    }

二:读取

/**
     * 通过id读取该条数据
     * @param id
     * @return
     */
    public ArticleEntity getContent(String id){
        PreparedStatement ps =null;
        ResultSet rs = null;
        Connection conn = null;
        Clob clob = null;
        ArticleEntity aae = new ArticleEntity ();
        String sql="SELECT * FROM TABLE WHERE ID = ?  ";
        try {
            conn =DBHelper.getMyConnection();
            ps = conn.prepareStatement(sql);
            ps.setString(1, id);
            rs = ps.executeQuery();
            while(rs.next()){
                aae.setId(rs.getString("ID"));
                clob = (oracle.sql.CLOB) rs.getClob("CONTENT"); 
                try {
                    if(clob !=null && clob != ""){
                        aae.setContent(ClobToString(clob));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return aae;
    }

    /**
     * 将字CLOB转成STRING类型 
     * @param clob
     * @return
     * @throws SQLException
     * @throws IOException
     */
    public String ClobToString(Clob clob) throws SQLException, IOException {
        String reString = "";
        Reader is = clob.getCharacterStream();// 得到流
        BufferedReader br = new BufferedReader(is);
        String s = br.readLine();
        StringBuffer sb = new StringBuffer();
        while (s != null) {
            sb.append(s);
            s = br.readLine();
        }
        reString = sb.toString();
        return reString;
    }

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值