Blob和Clob的使用
阿新 • • 發佈:2018-12-10
筆記
/* 1.LOB(Large Object,大型物件)型別的欄位現在用得越來越多了。因為這種型別的欄位,容量大(最多能容納4GB的資料),且一個表中可以有多個這種型別的欄位,很靈活,適用於資料量非常大的業務領域(如圖象、檔案等)。 2.LOB型別分為BLOB和CLOB兩種:BLOB即二進位制大型物件(Binary Large Object),適用於存貯非文字的位元組流資料(如程式、圖象、影音等)。 3.而CLOB,即字元型大型物件(Character Large Object),則與字符集相關,適於存貯文字型的資料(如歷史檔案、大部頭著作等)。 4. 四種類型的最大長度: tinyBlob:255, Blob:65k, MediumBlob:16M, LongBlob:4G text也是這4種類型,長度類似 create table note{ id int, note text; } 欄位定義成 "note varchar(100000)" 時,資料庫自動會把它轉成 MediumText型別 CREATE TABLE img( id INT, img BLOB //MEDIUMBLOB ); * */
//※凡是要寫入大資料欄位,都只能使用PreparedStatement, 不能使用Statement。讀取大資料欄位是可以用Statement的。
package cn.bl.v2; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import org.junit.Test; import cn.bl.DBUtil; public class LobDemo { //測試blob - 儲存 @Test public void saveBlob() throws Exception { Connection conn = DBUtil.getConnection(); String sql = " insert into img(image) values(?) "; PreparedStatement pst = conn.prepareStatement(sql); InputStream in = new FileInputStream(new File("E:/1.jpg")); pst.setBinaryStream(1, in); pst.execute(); conn.close(); } //測試blob - 讀取到硬碟 @Test public void readBlob() throws Exception { Connection conn = DBUtil.getConnection(); String sql = " select * from img "; Statement st = conn.createStatement(); ResultSet set = st.executeQuery(sql); while(set.next()) { System.out.println(set.getInt("id")); InputStream in = set.getBinaryStream("image"); OutputStream out = new FileOutputStream(new File("E:/2.jpg")); int len = -1; byte[]b = new byte[1024]; while((len=in.read(b))!=-1){ out.write(b, 0, len); } in.close(); out.close(); } } //測試clob @Test public void saveClob() throws Exception {//注意文字編碼是utf-8的,要對應mysql的 Connection conn = DBUtil.getConnection(); String sql = " insert into note(note) values(?) "; PreparedStatement pst = conn.prepareStatement(sql); InputStream in = new FileInputStream(new File("E:/1.txt")); pst.setAsciiStream(1, in); pst.execute(); in.close(); conn.close(); } @Test public void readClob() throws Exception { Connection conn = DBUtil.getConnection(); String sql = " select * from note where id = 1"; Statement st = conn.createStatement(); ResultSet set = st.executeQuery(sql); while(set.next()) { System.out.println(set.getInt(1)); InputStream in = set.getAsciiStream("note"); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String string = ""; while((string = bin.readLine())!=null){ System.out.println(string); } in.close(); } } }