数据库
首页 > 数据库> > c# – SQL数据库中的BLOB文件为块

c# – SQL数据库中的BLOB文件为块

作者:互联网

我尝试修改示例:link to example但我收到错误;无法将类型为’System.DBNull’的对象强制转换为’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);

标签:c,sql-server,uniqueidentifier
来源: https://codeday.me/bug/20190630/1335180.html