本文给出一个用 C# 编程实现读写 Binary 的实例代码对于初学者来说是个不可多得的参考性文章……
以下是引用片段//返回blob数据 public MemoryStream getBlob(string SQL) { try { Db_Conn(); cmd = new OleDbCommand(SQL Conn); cmdCommandType = CommandTypeText;//是sql OleDbDataReader Rs = cmdExecuteReader(); if (RsRead()) //循环到下一条记录 { if (!(RsGetValue() is SystemDBNull)) { byte[] image_bytes = (byte[])RsGetValue(); MemoryStream ms = new MemoryStream(image_bytes); return ms; } else return null; } else return null; } finally { thisclose(); } } //设置blob public bool SetBlob(string SQL MemoryStream Ms) { try { Db_Conn(); cmd = new OleDbCommand(SQL Conn); cmdCommandType = CommandTypeText;//是sql int n=ConvertToInt(MsLengthToString()); MsPosition = ; byte[] pReadByte = new Byte[n]; MsRead(pReadByte n); cmdParametersAdd(BLOB OleDbTypeBinary)Value = pReadByte; cmdExecuteNonQuery(); return true; } catch (Exception ex) { MessageBoxShow(错误:因 + exMessage + 无法执行: + SQL); return false; } finally { thisclose(); } }
调用 getBlob
以下是引用片段String sqlStr = select content from dp where id= + ID;
//content为dp中的BLOB字段ID为主键 MemoryStream ms = DBClassgetBlob(sqlStr); if (ms == null) richTextBoxClear(); else { if (msLength > ) { msPosition = ; try { richTextBoxLoadFile(ms RichTextBoxStreamTypeRichText); }catch{ richTextBoxLoadFile(ms RichTextBoxStreamTypePlainText); } }else richTextBoxClear(); }
调用setBlob
以下是引用片段String sqlStr = update dp set content=:BLOB where id= + ID; MemoryStream ms = new MemoryStream(); richTextBoxSaveFile(ms RichTextBoxStreamTypeRichText); if (!DBClassSetBlob(sqlStr ms)) { MessageBoxShow(保存失败); }