SQL数据库中的BLOB文件为块

时间:2012-02-08 20:12:44

标签: c# sql-server blob uniqueidentifier chunks

我尝试修改以下示例:link to example但我收到错误;
Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'我认为返回的ID(UniqueIdentifier)不正确。< br />
我的代码:

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;
    }
}

3 个答案:

答案 0 :(得分:2)

如另一个答案所述,这个例子已经过时了;我不建议使用它。

如果您已将其设置为仅作为练习使用,请更改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);

答案 1 :(得分:1)

这个例子已经过时了。在SQL Server 2005之后强烈建议不要使用TEXTPTR,以及不推荐使用的TEXT,NTEXT和IMAGE类型。正确的SQL Server 2005以及有效操作BLOB的方法之后是使用UPDATE .WRITE语法和MAX数据类型。如果您想查看示例,请查看Download and Upload images from SQL Server via ASP.Net MVC

答案 2 :(得分:1)

我发现了一种更好的方法here,这是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 是列名