这就是我将图像保存在 BLOB/Image DB 字段中的方法。
/// <summary>
/// Saves the file into a BLOB/Image field in the DB
/// This uses an UPDATE command, therefore the record must alreay exist in the DB
/// </summary>
/// <param name="aTableName"></param>
/// <param name="aFieldName"></param>
/// <param name="aWhereClause"></param>
/// <param name="aFileName"></param>
/// <returns></returns>
public bool SaveToBLOB(string aTableName, string aFieldName, string aWhereClause, string aFileName)
{
string sSQL = string.Format("UPDATE {0} SET {1}=@{1} WHERE {2}", aTableName, aFieldName, aWhereClause);
using (SqlCommand oComm = new SqlCommand(sSQL, m_Conn))
{
byte[] wFileAsByteArr = CDBConn.GetFileAsByteArray(aFileName);
oComm.Parameters.Add("@" + aFieldName, SqlDbType.Image, wFileAsByteArr.Length).Value = wFileAsByteArr;
return oComm.ExecuteNonQuery() > 0;
}
}
这就是我检索它的方式: /// /// 提取指定 SQL 命令的第一个字段 (BLOB) 并将其保存为文件 /// /// /// /// 如果文件已创建,则为 true否则为 false public bool ExtractBLOB(string aSQLCommand, string aFileName) { using (SqlCommand oComm = CreateCommand()) { oComm.CommandText = aSQLCommand; oComm.CommandType = CommandType.Text;
// Create a file to hold the output.
using (System.IO.FileStream fs = new System.IO.FileStream(aFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
{
using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))
{
byte[] b = (byte[])oComm.ExecuteScalar();
if (b != null)
{
bw.Write(b);
bw.Flush();
return true;
}
else
return false;
}
}
}
}
aSQLCommand 的位置:SELECT MyImageField FROM TableABC WHERE ...