日期:2014-05-16  浏览次数:20316 次

操作数据库的Blob数据 (文件, 图片等)
使用场景:
    数据库里面直接使用blob类型保存图片,文件等二进制文件,如何对这些数据进行插入,读取?

1. 插入: TSQL可以使用Openrowset,Bulk, 例如:
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:
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();