CREATE TABLE BlobTable (
ID CHAR(10) PRIMARY KEY,
Data IMAGE -- 不要用 TEXT,與二進位不相容
);
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()。com.microsoft.sqlserver.jdbc.SQLServerDriver) 或 jTDS。jdbc:sqlserver://localhost:1433;databaseName=MyDB;user=sa;password=***
掌握 BLOB 讀寫模式,可支援文件存儲、圖片管理、二進位日誌等常見業務場景。