SQL数据库中的BLOB文件作为区块
本文关键字:文件 BLOB 数据库 SQL | 更新日期: 2023-09-27 18:23:44
我试图将示例从:链接修改为示例,但收到错误Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'
我认为返回的ID(UniqueIdentifier)不正确
我的代码:
public static Guid AddRecord(string firstCol, DateTime SecCol, string photoFilePath)
{
using (SqlConnection connection = new SqlConnection(
"Data Source=(local);Integrated Security=true;Initial Catalog=Test;"))
{
SqlCommand addRec = new SqlCommand(
"INSERT INTO myTable (firstCol,SecCol,Image) " +
"VALUES (@firstCol,@SecCol,0x0)" +
"SELECT @Identity = NEWID();" +
"SELECT @Pointer = TEXTPTR(Image) FROM myTable WHERE ID = @Identity", connection);
addRec.Parameters.Add("@firstCol", SqlDbType.VarChar, 25).Value = firstCol;
addRec.Parameters.Add("@SecCol", SqlDbType.DateTime).Value = SecCol;
SqlParameter idParm = addRec.Parameters.Add("@Identity", SqlDbType.UniqueIdentifier);
idParm.Direction = ParameterDirection.Output;
SqlParameter ptrParm = addRec.Parameters.Add("@Pointer", SqlDbType.Binary, 16);
ptrParm.Direction = ParameterDirection.Output;
connection.Open();
addRec.ExecuteNonQuery();
Guid newRecID = (Guid)idParm.Value;
StorePhoto(photoFilePath, (byte[])ptrParm.Value, connection);
return newRecID;
}
}
正如另一个答案中所指出的,该示例已过时;我不建议使用它。
如果您打算将其作为练习来使用,请更改SQL以将您创建的ID插入myTable
,如下所示:
SqlCommand addRec = new SqlCommand(
"SELECT @Identity = NEWID();" +
"INSERT INTO myTable (ID,firstCol,SecCol,Image) " +
"VALUES (@Identity,@firstCol,@SecCol,0x0)" +
"SELECT @Pointer = TEXTPTR(Image) FROM myTable WHERE ID = @Identity", connection);
那个例子已经过时了。SQL Server 2005之后,强烈反对使用TEXTPTR
的USe,以及不推荐使用的TEXT、NTEXT和IMAGE类型。有效操作BLOB的正确SQL Server 2005及其之后的方法是使用UPDATE .WRITE
语法和MAX数据类型。如果您想查看示例,请查看通过ASP.Net MVC 从SQL Server下载和上载图像
我在这里找到了一个更好的方法,这是SQL Server 2005+的方法
string sql = "UPDATE BinaryData SET Data.Write(@data, LEN(data), @length) WHERE fileName=@fileName";
SqlParameter dataParam = cmd.Parameters.Add("@data", SqlDbType.VarBinary);
SqlParameter lengthParam = cmd.Parameters.Add("@length", SqlDbType.Int);
cmd.CommandText = sql;
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
int readBytes = 0;
while (cIndex < fileSize)
{
if (cIndex + BUFFER_SIZE > fileSize)
readBytes = fileSize - cIndex;
else
readBytes = BUFFER_SIZE;
fs.Read(buffer, 0, readBytes);
dataParam.Value = buffer;
dataParam.Size = readBytes;
lengthParam.Value = readBytes;
cmd.ExecuteNonQuery();
cIndex += BUFFER_SIZE;
}
BinaryData是表名。
Data.Write是一个系统函数调用,其中Data是列名