Blob內存放的是字節數組,需使用String的getBytes獲得該字符串的字節數組(注意字符集編碼),然后存入Blob。
Oracle的Blob字段比較特殊,他比long字段的性能要好很多,可以用來保存例如圖片之類的二進制數據。寫入Blob字段和寫入其它類型字段的方式非常不同,不能直接像插入其他普通類型數據一樣插入Blob字段數據,因為Blob相當於一個大文件塊,里面有游標cursor,你必須使用cursor對Blob進行操作,因而你在寫入Blob之前,必須獲得cursor。
具體操作步驟是,先插入一個empty的Blob,這將創建一個Blob的cursor,然后你再把這個empty的Blob的cursor用select查詢出來,這樣通過兩步操作,你就獲得了Blob的cursor,可以真正地寫入Blob數據了。
public static void instertStringIntoBlob(String str) { try { //獲得字符串的字節數組 byte[] value = null; value = str.getBytes(); //數據庫連接 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,創建cursor String sql1 = "insert into test(id,content) values('999',empty_blob())"; Statement statement = con.createStatement(); statement.execute(sql1); //select獲得cursor,並寫入數據 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) { } }