Npgsql 读写大对象

Npgsql管理大对象

1.写大对象

using (NpgsqlConnection conn = new NpgsqlConnection(GetConnectString()))
{
try
{
conn.Open();


int noid;


using (NpgsqlTransaction trans = conn.BeginTransaction())
{
try
{
LargeObjectManager lom = new LargeObjectManager(conn);
byte[] buf = new byte[8192];
int readIn = 0;
int noid = lom.Create(LargeObjectManager.WRITE);
LargeObject lo = lom.Open(noid, LargeObjectManager.WRITE);
using (FileStream fs = File.OpenRead(fileName))
{
while ((readIn = fs.Read(buf, 0, buf.Length)) > 0)
{
lo.Write(buf, 0, readIn);
}
}
lo.Close();
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
catch (NpgsqlException ex)
{
MessageBox.Show(ex.Message, "数据库错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}


2.读对象

using (NpgsqlConnection conn = new NpgsqlConnection(GetConnectString()))
{
try
{
conn.Open();
using (NpgsqlTransaction trans = conn.BeginTransaction())
{
LargeObjectManager lom = new LargeObjectManager(conn);
LargeObject lo = lom.Open(rfi.LargeObject, LargeObjectManager.READ);
using (FileStream fs = File.OpenWrite(@"D:\1.png"))
{
int tempmax = lo.Size();
int tempread = 0;
int temppos = 0;


do
{
byte[] buf = lo.Read(8192);
tempread = buf.Length;
if (tempread > 0)
{
fs.Write(buf, 0, tempread);
temppos += tempread;
lo.Seek(temppos);
}
} while (tempread > 0);
fs.Flush();
}
lo.Close();
trans.Commit();
}
}
catch (NpgsqlException ex)
{
MessageBox.Show(ex.Message, "数据库错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}

//注意,读也必须执行事务,否则执行lo.Size()会出现错误。返回无效的大对象描述


3.删除对象

 using (NpgsqlConnection conn = new NpgsqlConnection(GetConnectString()))
            {
                try
                {
                    conn.Open();


                    using (NpgsqlTransaction trans = conn.BeginTransaction())
                    {
                        LargeObjectManager lom = new LargeObjectManager(conn);
                        lom.Delete(noid);
                        trans.Commit();
                    }
                }
                catch (NpgsqlException ex)
                {
                    MessageBox.Show(ex.Message, "数据库错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }


1,2经过测试,visual Studio 2012 .net 4.0.3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值