首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

Java 操作 SQL Server 2000 大型二進位物件 (BLOB) 完整範例

     編輯:關於SqlServer

資料表設計

CREATE TABLE BlobTable (
    ID   CHAR(10) PRIMARY KEY,
    Data IMAGE  -- 不要用 TEXT,與二進位不相容
);

Java 完整代碼 (JDBC-ODBC Bridge 示範)

import java.io.*;
import java.sql.*;

public class BlobInsert {
    public static void main(String[] args) {
        String filePath = "D:\\test1.txt";
        String sql = "INSERT INTO BlobTable (ID, Data) VALUES ('0004', ?)";
        new BlobInsert().insert(filePath, sql);
    }

    public void insert(String filePath, String sql) {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection conn = DriverManager.getConnection("jdbc:odbc:LW"); // DSN 名稱

            // 讀取檔案為位元組陣列
            byte[] data = readFileBytes(filePath);

            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setBytes(1, data);
            ps.executeUpdate();

            ps.close();
            conn.close();
            System.out.println("BLOB 寫入成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private byte[] readFileBytes(String path) throws IOException {
        FileInputStream fis = new FileInputStream(path);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        int len;
        while ((len = fis.read(buf)) != -1) bos.write(buf, 0, len);
        fis.close();
        return bos.toByteArray();
    }
}

關鍵點總結

  • 欄位型別用 IMAGE (SQL Server 2000) / VARBINARY(MAX) (2005+),不可用 TEXT/NTEXT。
  • 使用 PreparedStatement.setBytes() 或 setBinaryStream() 寫入二進位資料。
  • 讀取時用 ResultSet.getBytes() 或 getBinaryStream()。
  • JDBC-ODBC Bridge 已淘汰,生產環境請改用 Microsoft JDBC Driver (com.microsoft.sqlserver.jdbc.SQLServerDriver) 或 jTDS。
  • 大檔案建議分塊流式讀寫,避免記憶體溢位 (OOM)。

現代驅動連接字串範例

jdbc:sqlserver://localhost:1433;databaseName=MyDB;user=sa;password=***

掌握 BLOB 讀寫模式,可支援文件存儲、圖片管理、二進位日誌等常見業務場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved