.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; }
}

 

image

本文由作者:陈希章 于 2009/7/9 16:32:00 发布在:http://www.cnblogs.com/chenxizhang/
本文版权归作者所有,可以转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
更多博客文章,以及作者对于博客引用方面的完整声明以及合作方面的政策,请参考以下站点:陈希章的博客中心
posted @ 2009-07-09 16:32  陈希章  阅读(3715)  评论(1编辑  收藏  举报