1. 程式人生 > >oracle使用java操作clob型別的欄位

oracle使用java操作clob型別的欄位

插入

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;
    }