---
title: "操作数据库的Blob数据 （文件， 图片等）"
author: "JavaFans"
date: "2010-04-21T15:00:53Z"
tags: []
categories: ["数据库"]
slug: "blob"
draft: false
lastmod: "2010-08-27T15:15:03Z"
id: 649448
url: "https://javafans.iteye.com/blog/649448"
---

使用场景：
    数据库里面直接使用blob类型保存图片，文件等二进制文件，如何对这些数据进行插入，读取？

1. 插入： TSQL可以使用Openrowset,Bulk， 例如：

```SQL

CREATE TABLE [sblob] (
      [cabdata] [image] NULL 
) ON [primary] TEXTIMAGE_ON [primary]
GO

INSERT INTO [sblob] ([cabdata])
      SELECT 
            BulkColumn FROM OPENROWSET(
                  Bulk 'C:\MyCab.zip', SINGLE_BLOB) AS BLOB

```

2. 读取：将数据库值读取为文件
    在SQL Server 2000和之前，可以使用TextCopy命令。
但是微软在SQL Server 2005及以后，不再有这个命令。因此比较麻烦。
但是如果用.net可以很方便的实现这个功能。
sample code:

```c#

int IndexBlobContents = 0;
sqlconn.ConnectionString = "Server=" + ServerName + ";UID=" + UID + ";Pwd=" + Pwd + ";Database=" + DBName;
sqlconn.Open();

Blobsize = 10000000;// Initalize the BlobSize
cmd = new SqlCommand("SELECT " + Fldnames + " FROM " + TbName + " " + Cndt, sqlconn);
sqlDr = cmd.ExecuteReader();
while (sqlDr.Read())
{
    //dirname + filename
    ExtractFileName = ExtractPath + sqlDr[1].ToString();
    startIndex = 0; // Reset the starting byte for the new BLOB.
    outBuffer = new byte[blobsize];
    if (File.Exists(@ExtractFileName))
    {
        File.Delete(@ExtractFileName);
    }

    // Create a file to hold the output.
    fs = new FileStream(@ExtractFileName, FileMode.OpenOrCreate, FileAccess.Write); 
    bw = new BinaryWriter(fs);

    // Read bytes into outByte[] and retain the number of bytes returned.
    blob = sqlDr.GetBytes(IndexBlobContents, startIndex, outBuffer, 0, Blobsize); 
    while (blob == Blobsize) // Continue while there are bytes beyond the size of the buffer.
    {
        bw.Write(outBuffer);
        bw.Flush();
        startIndex += Blobsize;
        blob = sqlDr.GetBytes(IndexBlobContents, startIndex, outBuffer, 0, Blobsize);
    }

    // Write the remaining buffer.
    bw.Write(outBuffer, 0, (int)blob);
    bw.Flush();
    bw.Close();
    fs.Close();
}
sqlDr.Close();

```