Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 操作 MySQL 大文本與二進位資料:TEXT 與 BLOB 讀寫全解

在 MySQL 裡,一般字串欄位用 VARCHAR 就足夠了,但它的上限是 65535 個位元組。一旦要存整份程式碼、長篇本文或商品描述,就會撞上這道天花板,這時就該換成 TEXT 家族;若內容再誇張,LONGTEXT 最大可承載約 4GB。二進位資料(圖片、音訊、影片)則交給 BLOB 家族,LONGBLOB 同樣能到 4GB 等級。

一、TEXT(CLOB)的存取

寫入大文本

關鍵在於 setCharacterStream:把一個 Reader 直接交給 JDBC 串流式寫入,不必先把整份檔案讀進記憶體。

String sql = "insert into clob(file) value(?)";
PreparedStatement ps = conn.prepareStatement(sql);

File file = new File("res/ClobDemo.java");
Reader reader = new FileReader(file);

ps.setCharacterStream(1, reader, (int) file.length());
ps.executeUpdate();

reader.close(); // 最後一定要關流

讀取大文本

查詢後用 getCharacterStream 取回一個 Reader,它就是通往資料庫內容的資料流,後續只要操作這個流即可。

String sql = "select file from clob";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();

if (rs.next()) {
    Reader r = rs.getCharacterStream(1);
    // 這個 Reader 就是從資料庫讀取資料的流
    BufferedReader br = new BufferedReader(r);
    BufferedWriter bw = new BufferedWriter(new FileWriter("res/new.txt"));

    String s = "";
    while ((s = br.readLine()) != null) {
        bw.write(s + "\n");
    }

    bw.flush();
    br.close();
    r.close();
    bw.close();
}

實務上建議用 try-with-resources 管理這些流,避免例外發生時洩漏連線與檔案 handle。

二、BLOB 的存取

寫入二進位檔

PreparedStatement ps = conn.prepareStatement("insert into big_binary(file) values(?)");
File file = new File("src/cn/itcast/jdbc1/clob_blob/IMG_0007.jpg");
InputStream in = new FileInputStream(file);

ps.setBinaryStream(1, in, (int) file.length());
ps.executeUpdate();

讀取二進位檔並落地

PreparedStatement ps = conn.prepareStatement("select file from big_binary");
ResultSet rs = ps.executeQuery();

if (rs.next()) {
    InputStream in = rs.getBinaryStream(1);
    // 這個 InputStream 就是從資料庫讀取資料的流
    File file = new File("res/newgirl.jpg");
    FileOutputStream fos = new FileOutputStream(file);

    int num = in.available();
    byte buffer[] = new byte[num];
    while (in.read(buffer, 0, num) != -1) {
        fos.write(buffer);
    }

    in.close();
    fos.close();
}

兩個實務提醒

第一,範例中的 available() 回傳的是「目前不阻塞就能讀到的位元組數」,並不等於檔案總長度,正式環境請改用固定大小緩衝區(例如 4096 或 8192)反覆讀寫,並以 read 的回傳值控制迴圈。

第二,把大檔案塞進資料庫會讓備份、還原與查詢都變重,多數大型系統會選擇把檔案放在檔案系統或物件儲存服務,資料庫只存路徑;TEXT/BLOB 更適合中小型內容或需要與資料列同生共死的情境。

Copyright © Linux教程網 All Rights Reserved