資料庫 BLOB 欄位常用於儲存圖片、文件、RichText 等二進位資料。本文提供完整的 C# 範例,示範如何使用 OleDbCommand 搭配 MemoryStream 讀寫 BLOB,並處理 RichTextBox 的 RTF/純文字雙格式相容。
public class DBClass
{
private OleDbConnection Conn;
private OleDbCommand cmd;
private void Db_Conn()
{
// 連線字串略,請依實際資料庫設定
Conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb");
}
private void close()
{
if (Conn != null && Conn.State == ConnectionState.Open)
Conn.Close();
}
///
/// 讀取 BLOB 回傳 MemoryStream
///
public MemoryStream getBlob(string SQL)
{
try
{
Db_Conn();
cmd = new OleDbCommand(SQL, Conn);
cmd.CommandType = CommandType.Text;
OleDbDataReader Rs = cmd.ExecuteReader();
if (Rs.Read())
{
if (!(Rs.GetValue(0) is DBNull))
{
byte[] image_bytes = (byte[])Rs.GetValue(0);
return new MemoryStream(image_bytes);
}
}
return null;
}
finally
{
this.close();
}
}
///
/// 寫入 BLOB
///
public bool SetBlob(string SQL, MemoryStream Ms)
{
try
{
Db_Conn();
cmd = new OleDbCommand(SQL, Conn);
cmd.CommandType = CommandType.Text;
int n = (int)Ms.Length;
Ms.Position = 0;
byte[] pReadByte = new byte[n];
Ms.Read(pReadByte, 0, n);
cmd.Parameters.Add("BLOB", OleDbType.Binary).Value = pReadByte;
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
MessageBox.Show("錯誤:因 " + ex.Message + ",無法執行:" + SQL);
return false;
}
finally
{
this.close();
}
}
}
string sqlStr = "select content from dp where id=" + ID; // content 為 BLOB 欄位
MemoryStream ms = DBClass.getBlob(sqlStr);
if (ms == null || ms.Length == 0)
{
richTextBox.Clear();
}
else
{
ms.Position = 0;
try
{
// 嘗試載入 RTF 格式
richTextBox.LoadFile(ms, RichTextBoxStreamType.RichText);
}
catch
{
// 失敗則嘗試純文字
ms.Position = 0;
richTextBox.LoadFile(ms, RichTextBoxStreamType.PlainText);
}
}
string sqlStr = "update dp set content=:BLOB where id=" + ID;
MemoryStream ms = new MemoryStream();
// 存為 RTF 格式(保留格式)
richTextBox.SaveFile(ms, RichTextBoxStreamType.RichText);
if (!DBClass.SetBlob(sqlStr, ms))
{
MessageBox.Show("儲存失敗");
}
cmd.Parameters.Add("BLOB", OleDbType.Binary) 防止 SQL Injection 並正確傳遞二進位資料。Position = 0,否則會從當前位置開始導致資料遺漏或覆寫錯誤。finally 區塊確保連線關閉,避免連線洩漏。SqlFileStream (Filestream) 或分塊讀寫,避免記憶體壓力。SqlConnection/SqlCommand,效能優於 OleDb。ExecuteReaderAsync/ReadAsync 提升 UI 回應性。byte[] 對應 BLOB,自動處理參數化與變更追蹤。掌握 MemoryStream 搭配 ADO.NET 參數化命令讀寫 BLOB,是處理資料庫二進位資料的基本功。範例展示的 RTF/純文字雙模式相容、資源正確釋放、錯誤處理等細節,能直接套用於實務專案中。