C#对Oracle BLOB字段的写入读取方法

1.写入BLOB:
    string  file_name  =   " D:\\20080523.jpg " ;
   
string  conn_str  =   " Provider=OraOLEDB.Oracle.1;Password=agoodjob;Persist Security Info=True;User ID=ams;Data Source=ims;Extended Properties= " ; // Provider必須用OraOLEDB.Oracle.1
   OleDbConnection cn  =   new  OleDbConnection(conn_str);
   cn.Open();

   OleDbCommand cmd 
=   new  OleDbCommand( " UPDATE BLOB SET PHOTO = ?  " ,cn);
   cmd.Parameters.Add(
" PHOTO " ,OleDbType.Binary);   
   
   FileStream fs 
=   new  FileStream(file_name, FileMode.OpenOrCreate, FileAccess.Read);
   
byte [] MyData =   new   byte [fs.Length];
   fs.Read(MyData, 
0 , System.Convert.ToInt32(fs.Length));
   fs.Close();

   cmd.Parameters[
" PHOTO " ].Value  =  MyData;
   
try  
   {
    
int  result  =  cmd.ExecuteNonQuery();
    
if (result < 1 )
    {
     OleDbCommand cmd1 
=   new  OleDbCommand( "  INSERT INTO BLOB (PHOTO) VALUES ( ? ) " ,cn);
     cmd1.Parameters.Add(
" PHOTO " ,OleDbType.Binary);
     cmd1.Parameters[
" PHOTO " ].Value  =  MyData;
     result 
=  cmd1.ExecuteNonQuery();
    }
   }  
   
catch (Exception e1)
   {
    Page.RegisterStartupScript(
"" , " <script language='javascript'>alert(' " + e1.Message + " ')</script> " );
   }
   
finally
   {
    cn.Close();
   }

2.读取BLOB:
    string  conn_str  =   " Provider=OraOLEDB.Oracle.1;Password=agoodjob;Persist Security Info=True;User ID=ams;Data Source=ims;Extended Properties= " ; // Provider必須用OraOLEDB.Oracle.1
   
   OleDbDataAdapter da 
=   new  OleDbDataAdapter();
   DataSet ds 
=   new  DataSet();
   OleDbConnection conn 
=   new  OleDbConnection(conn_str);
   OleDbCommand cmd 
=   new  OleDbCommand( " SELECT PHOTO FROM WEB_DB.USERS WHERE USER_ID = 1 " , conn);
   da.SelectCommand 
=  cmd;
   cmd.Connection.Open();
   da.Fill(ds);

   
byte [] img  =   new   byte [ 0 ];
   DataRow dr;
   dr 
=  ds.Tables[ 0 ].Rows[ 0 ];

   
if  ( ! ds.Tables[ 0 ].Rows[ 0 ][ " PHOTO " ].ToString().Equals( "" ))
   {
    img 
=   ( byte [])dr[ " PHOTO " ];
   }

   Response.ContentType
=   " image/* " ;
   Response.BinaryWrite (img);

   conn.Close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值