当我运行这段代码时,我需要运行最后一条SQL语句来从blob中删除一个空字节。为什么我在FileBytes(varchar(max))字段的末尾有这个空字节是没有意义的。
代码有效。出于好奇,为什么我需要最后一个语句来摆脱空字节。或者我错过了为什么它在那里。
这是我的代码。
public static void SaveBlob(DbConnection connection, DbTransaction trans, Guid attachmentGuid, Stream stream)
{
int bufferLen = 8040; //Recommended size from MSDN (multiples of 8040)
string sql = "UPDATE Attachments ";
sql += "SET FileBytes .WRITE(@Bytes, @Offset, 0) ";
sql += "WHERE Attachments.AttachmentGUID = @AttachmentGUID";
using (DbCommand command = connection.CreateCommand())
{
command.Transaction = trans;
command.CommandText = sql;
// Read the image in and write it to the database 128 (bufferLen) bytes at a time.
// Tune bufferLen for best performance. Larger values write faster, but
// use more system resources.
BinaryReader br = new BinaryReader(stream);
byte[] buffer = br.ReadBytes(bufferLen);
int offset = 0;
DbParameter blobParam = command.AddParameter("@Bytes", stream);
blobParam.Size = buffer.Length;
DbParameter offsetParam = command.AddParameter("@Offset", offset);
command.AddParameter("@AttachmentGUID", attachmentGuid);
int offset_ctr = 0;
while (buffer.Length > 0)
{
blobParam.Size = buffer.Length;
blobParam.Value = buffer;
command.ExecuteNonQuery();
offset_ctr += bufferLen;
offsetParam.Value = offset_ctr;
buffer = br.ReadBytes(bufferLen);
}
//Need one more
//Removes last byte (empty and extra)
//I do not understand why I need this
sql = "UPDATE Attachments ";
sql += "SET FileBytes .WRITE(NULL, " + stream.Length.ToString() + @", 1) ";
sql += "WHERE Attachments.AttachmentGUID = @AttachmentGUID ";
sql += "AND DATALENGTH(FileBytes) > " + stream.Length.ToString();
command.CommandText = sql;
command.Parameters.Clear();
command.AddParameter("@AttachmentGUID", attachmentGuid);
command.ExecuteNonQuery();
br.Close();
}
}