对oracle中的BLOB的操作(读取,写入)

 将BLOB保存为本地文档:

///

/// 读出Blob字段 /// /// sql语句,执行结果为BLOB数据 /// 将要把BLOB数据保存为的文档的路径 public void ReadBlob(string commandText, string DocumentAddress) { try { Open(); cmd.Connection = conn; cmd.CommandType = CommandType.Text; cmd.CommandText = commandText; // 利用事务处理(必须) OracleTransaction transaction = cmd.Connection.BeginTransaction(); cmd.Transaction = transaction; reader = cmd.ExecuteReader(); reader.Read(); OracleLob BLOB = reader.GetOracleLob(0); reader.Close(); FileStream DataStream = new FileStream(DocumentAddress, FileMode.Create); int length = 30485760; byte[] Buffer = new byte[length]; int i; while ((i = BLOB.Read(Buffer, 0, length)) > 0) { DataStream.Write(Buffer, 0, i); } DataStream.Close(); BLOB.Clone(); cmd.Transaction.Commit(); } catch (OracleException e) { cmd.Transaction.Rollback(); throw e; } finally { Close(); } }

 

将本地文档保存为BLOB类型:

///

/// 写入Blob字段 /// /// sql语句,执行结果为BLOB数据 /// 本地文档的路径 public void WriteBlob(string commandText, string DocumentAddress) { try { Open(); cmd.Connection = conn; cmd.CommandType = CommandType.Text; cmd.CommandText = commandText; // 利用事务处理(必须) OracleTransaction transaction = cmd.Connection.BeginTransaction(); cmd.Transaction = transaction; reader = cmd.ExecuteReader(); using (reader) { //Obtain the first row of data. reader.Read(); OracleLob BLOB = reader.GetOracleLob(0); //Perform any desired operations on the LOB, //(read,position, and so on).... //Example - Writing binary data (directly to the backend). //To write, you can use any of the stream classes, //or write raw binary data using the OracleLob write //method. Writing character vs. binary is the same;however //note that character is always in terms of Unicode byte counts FileStream DataStream = new FileStream (DocumentAddress,FileMode.Open); BLOB.BeginBatch(OracleLobOpenMode.ReadWrite); int length = 30485760; byte[] Buffer = new byte[length]; int i; while ((i = DataStream.Read(Buffer, 0, length)) > 0) { BLOB.Write(Buffer, 0, i); } DataStream.Close(); BLOB.EndBatch(); //Commit the transaction now that everything succeeded. //Note: On error, Transaction.Dispose is called //(from the using statement) //and will automatically roll-back the pending transaction. cmd.Transaction.Commit(); } } catch (OracleException e) { cmd.Transaction.Rollback(); throw e; } finally { Close(); } }

你可能感兴趣的:(数据库应用,oracle,buffer,character,byte,string,文档)