oracle使用java操作clob类型的字段

来源:互联网 发布:诺基亚n96软件下载 编辑:程序博客网 时间:2024/06/11 20:12

插入

public static void insert(String id, String name,String clob_content) {        Writer outStream = null;        // 通过JDBC获得数据库连接        try {            Class.forName("oracle.jdbc.driver.OracleDriver");            Connection con = DriverManager.getConnection(                            "jdbc:oracle:thin:192.168.50.18/test",                            "root", "123456");            con.setAutoCommit(false);            Statement st = con.createStatement();            // 插入一个空对象empty_clob(),这个是必须的            // insert into EMS_CUST_JS(cust_code, js_name,            // js_content)values('','', empty_clob())            st.executeUpdate("insert into text(id, name, clob_content)values"                            + "('"+ id + "','" + name + "', empty_clob())");            // 锁定数据行进行更新,注意“for update”语句,这里不用for update锁定不可以插入clob            ResultSet rs = st.executeQuery("select clob_content from text where id='"+ id+                             "' and name='"+ name+                             "' for update");            if (rs.next()) {                // 得到java.sql.Clob对象后强制转换为oracle.sql.CLOB                oracle.sql.CLOB clob = (oracle.sql.CLOB) rs.getClob("clob_content");                outStream = clob.getCharacterOutputStream();                // clob_content是传入的字符串                char[] c = clob_content.toCharArray();                outStream.write(c, 0, c.length);            }            outStream.flush();            outStream.close();            con.commit();            con.close();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }

读取

public static String read() throws Exception {        String data = null;        Reader inStream = null;        // 获得数据库连接        Class.forName("oracle.jdbc.driver.OracleDriver");        Connection con = DriverManager.getConnection(                        "jdbc:oracle:thin:192.168.50.18/test",                        "root", "123456");        con.setAutoCommit(false);        Statement st = con.createStatement();        // 不需要“for update”        ResultSet rs = st.executeQuery("select CLOB_CONTENT from TEXT where ID=1");        if (rs.next()) {            java.sql.Clob clob = rs.getClob("CLOB_CONTENT");            inStream = clob.getCharacterStream();            char[] c = new char[(int) clob.length()];            inStream.read(c);            // data是读出并需要返回的数据,类型是String            data = new String(c);            inStream.close();        }        inStream.close();        con.commit();        con.close();        return data;    }
0 0
原创粉丝点击