csharp读写sqlserver数据库中的image列[转]

数据库表结构:

if exists (select name from sysobjects where name = 'content' and type = 'u')
 drop table content
go

create table content
(
 --内容id
 id bigint identity(1,1) not null,
 --内容
 data image default null,
  constraint pk_contentid primary key clustered (id)
)

go

const string cnnstr = "provider=sqloledb.1;user id=sa;password=;initial catalog=mydb;data source=(local)";

写入

public bool writecontent(byte [] data)
  {   
   oledbconnection conn = new oledbconnection(cnnstr);
   string myselectquery = "insert into content(data)values(?)";
   oledbcommand mycommand = new oledbcommand(myselectquery, conn);
   mycommand.commandtimeout = 60;
   
   
   oledbparameter param = new oledbparameter("@data", oledbtype.varbinary, data.length);    
   param.direction = parameterdirection.input;
   param.value = data;
   
   mycommand.parameters.add(param);
   bool ret = false;

   try
   { 
    conn.open();
    mycommand.executenonquery();
    ret = true;
   }
   catch(exception e)
   {
    string msg = e.message;
   }
   finally
   {
    //关闭数据库连接
    if((conn != null) && (conn.state != connectionstate.closed))
    {
     conn.close();
    } 
   }
   return ret;
  }

读出

private byte [] readcontent(int64 contentid)
  {
   byte [] buff = null;
   oledbconnection conn = new oledbconnection(cnnstr );
   string querystr = string.format("select data from content where id={0}", contentid);
  oledbcommand mycommand = new oledbcommand(querystr, conn);
   mycommand.commandtimeout = 60;
   oledbdatareader reader = null;
   long datalen = 0l;
   try
   { 
    conn.open();
    reader = mycommand.executereader();
    if( reader.read() )
    {
     //得到要读的数据长度,注意buff必须是空的引用
     datalen = reader.getbytes(0, 0, buff, 0, 1);
     //分配缓冲区
     buff = new byte[datalen];
     //读数据
     datalen = reader.getbytes(0, 0, buff, 0, (int)datalen);
    }    
   }
   catch(exception e)
   {
    internalerror(e);
    string msg = e.message;
   }
   finally
   {
    //关闭数据集
    if(reader != null && !reader.isclosed)
     reader.close();
    //关闭数据库连接
    if((conn != null) && (conn.state != connectionstate.closed))
    {
     conn.close();
    } 
   }
   return buff;
  }

posted on 2007-10-20 10:43  Timanders  阅读(1287)  评论(0编辑  收藏  举报

导航