.NET : 存取BLOB数据(Oracle)
下面是我写好的两个代码例子,分别对应了写入BLOB,和读取BLOB
public static void AddProduct(int id, string name, string desc, byte[] contents)
{
try
{
using (OracleConnection conn = new OracleConnection(transactionConnection))
{
conn.Open();
OracleTransaction tran = conn.BeginTransaction();
//这个事务是必须要使用的,否则无法提交成功
using (OracleCommand cmd = conn.CreateCommand())
{
///先用一个empty_blob(),填充一个空块
cmd.CommandText = string.Format("INSERT INTO SALES.Products VALUES(" +
"{0},'{1}','{2}',empty_blob())", id, name, desc);
cmd.ExecuteNonQuery();
///再读取,更新
cmd.CommandText = string.Format(
"SELECT Photo FROM SALES.Products WHERE ProductID={0} FOR UPDATE",
id);
OracleDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
OracleBlob blob = (OracleBlob)reader.GetOracleBlob(0);
blob.Write(contents, 0, contents.Length);
}
reader.Close();
tran.Commit();//提交事务
conn.Close();
}
}
}
catch
{
throw;
}
}
public static byte[] GetProductPhoto(int id)
{
try
{
using (OracleConnection conn = new OracleConnection(transactionConnection))
{
using (OracleCommand cmd = conn.CreateCommand())
{
cmd.CommandText = string.Format("SELECT ProductId,Photo FROM SALES.Products WHERE ProductID={0}", id);
conn.Open();
OracleDataReader reader = cmd.ExecuteReader();
byte[] buffer= new byte[50];
MemoryStream ms = new MemoryStream();
if (reader.Read())
{
OracleBlob blob = (OracleBlob)reader.GetOracleBlob(1);
while (blob.Read(buffer, 0, 50) > 0)
{
ms.Write(buffer, 0, buffer.Length);
}
blob.Close();
}
reader.Close();
conn.Close();
ms.Position = 0;
byte[] result = new byte[ms.Length];
ms.Read(result, 0, result.Length);
return result;
}
}
}
catch { throw; }
}