Blob內(nèi)存放的是字節(jié)數(shù)組,需使用String的getBytes獲得該字符串的字節(jié)數(shù)組(注意字符集編碼),然后存入Blob。

Oracle的Blob字段比較特殊,他比long字段的性能要好很多,可以用來保存例如圖片之類的二進(jìn)制數(shù)據(jù)。寫入Blob字段和寫入其它類型字段的方式非常不同,不能直接像插入其他普通類型數(shù)據(jù)一樣插入Blob字段數(shù)據(jù),因?yàn)锽lob相當(dāng)于一個(gè)大文件塊,里面有游標(biāo)cursor,你必須使用cursor對Blob進(jìn)行操作,因而你在寫入Blob之前,必須獲得cursor。

具體操作步驟是,先插入一個(gè)empty的Blob,這將創(chuàng)建一個(gè)Blob的cursor,然后你再把這個(gè)empty的Blob的cursor用select查詢出來,這樣通過兩步操作,你就獲得了Blob的cursor,可以真正地寫入Blob數(shù)據(jù)了。

public static void instertStringIntoBlob(String str) {
        try {
            //獲得字符串的字節(jié)數(shù)組
            byte[] value = null;
            value = str.getBytes();
            //數(shù)據(jù)庫連接
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
            String username = "scott";
            String password = "scott";
            Connection con = DriverManager.getConnection(url, username, password);
            con.setAutoCommit(false);
            //插入空Blob,創(chuàng)建cursor
            String sql1 = "insert into test(id,content) values('999',empty_blob())";
            Statement statement = con.createStatement();
            statement.execute(sql1);
            //select獲得cursor,并寫入數(shù)據(jù)
            String sql2 = "select content from test where id=999 for update";
            PreparedStatement stmt = con.prepareStatement(sql2);
            ResultSet rs = stmt.executeQuery();
            OutputStream outStream = null;
            if (rs.next()) {
                BLOB blob = (BLOB) rs.getBlob(1);
                outStream = blob.getBinaryOutputStream();
                outStream.write(value, 0, value.length);
            }
            outStream.flush();
            outStream.close();
            con.commit();
            con.close();
        } catch (Exception e) {
        }
    }