這是我如何將圖像保存在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}[email protected]{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如果文件被創建,否則爲假 公共BOOL ExtractBLOB(串aSQLCommand,串aFileName) { 使用(的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 ...
謝謝你的分享,但我希望在SQL服務器20102. –
邁克爾·莫雷諾執行查詢。 –