您的位置:首页 > 技术教程 > c#

用 C# 编程实现读写Binary
【字体: 整理日期:2007-12-3 8:56:50 打印本文】 【收藏此文

  本文给出一个用 c# 编程实现读写 binary 的实例代码,对于初学者来说是个不可多得的参考性文章……

以下是引用片段:
  //返回blob数据
  public memorystream getblob(string sql)
  ...{
  try
  ...{
  db_conn();
  cmd = new oledbcommand(sql, conn);
  cmd.commandtype = commandtype.text;//是sql
  oledbdatareader rs = cmd.executereader();
  if (rs.read()) //循环到下一条记录
  ...{
  if (!(rs.getvalue(0) is system.dbnull))
  ...{
  byte[] image_bytes = (byte[])rs.getvalue(0);
  memorystream ms = new memorystream(image_bytes);
  return ms;
  }
  else
  return null;
  }
  else
  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;//是sql
  int n=convert.toint32(ms.length.tostring());
  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();
  }
  }


  调用 getblob

以下是引用片段:
  string sqlstr = "select content from dp where id=" + id;//content为dp中的blob字段,id为主键
  memorystream ms = dbclass.getblob(sqlstr);
  if (ms == null)
  richtextbox.clear();
  else
  ...{
  if (ms.length > 0)
  ...{
  ms.position = 0;
  try
  ...{
  richtextbox.loadfile(ms, richtextboxstreamtype.richtext);
  }catch...{
  richtextbox.loadfile(ms, richtextboxstreamtype.plaintext);
  }
  }else
  richtextbox.clear();
  }


  调用setblob

以下是引用片段:
  string sqlstr = "update dp set content=:blob where id=" + id;
  memorystream ms = new memorystream();
  richtextbox.savefile(ms, richtextboxstreamtype.richtext);
  if (!dbclass.setblob(sqlstr, ms))
  ...{
  messagebox.show("保存失败");
  }


查询
关键词:
相关文章
标签Tags