将表列插入数据库后为System.DBNull

时间:2018-11-21 17:48:21

标签: c# sql oracle types dbnull

我有一个看起来像这样的表:

CREATE TABLE largeObject(
  fileName varchar2(50) primary key,
  fileContent blob,
  encrypthedFileContent blob
);

这是我的课程:

public class Blob
{
    public string FileName { get; private set; }
    public byte[] Binary { get; private set; }
    public byte[] EncryptedBinary { get; private set; }
    public Blob(string fileName, byte[] binary, byte [] encryptedBinary)
    {
        this.FileName = fileName;
        this.Binary = binary;
        this.EncryptedBinary = encryptedBinary;
    }

    public Blob(string FileName)
    {
        this.FileName = FileName;
    }

    public override string ToString()
    {
        return FileName;
    }

}

使用此代码,我从数据库中添加并加载表值:

    private static byte[] encrypth(byte[] input)
    {
        PasswordDeriveBytes pdb = new PasswordDeriveBytes("mycoolpassword", new byte[] { 0x43, 0x87, 0x23, 0x72 });
        MemoryStream ms = new MemoryStream();
        Aes aes = new AesManaged();
        aes.Key = pdb.GetBytes(aes.KeySize / 8);
        aes.IV = pdb.GetBytes(aes.BlockSize / 8);
        CryptoStream cs = new CryptoStream(ms,
          aes.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(input, 0, input.Length);
        cs.Close();
        return ms.ToArray();
    }

    public static Blob ConvertToBlob(string filePath)
    {

        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); //A stream of bytes that represnts the binary file
        BinaryReader reader = new BinaryReader(fs);  //The reader reads the binary data from the file stream
        byte[] binary = reader.ReadBytes((int)fs.Length);  //Bytes from the binary reader stored in BlobValue array

        fs.Close();
        reader.Close();
        return new Blob(filePath, binary,encrypth(binary));
    }

    public static void SaveToDb(string filePath)
    {
        Blob blob = ConvertToBlob(filePath);

        OleDbCommand cmd = new OleDbCommand("insert into largeObject values(:fileName, :fileContent, :encrypthedFileContent)", conn);

        cmd.Parameters.Add(new OleDbParameter(":fileName", Path.GetFileName(blob.FileName)));
        cmd.Parameters.Add(new OleDbParameter(":fileContent", blob.Binary));
        cmd.Parameters.Add(new OleDbParameter(":encrypthedFileContent", blob.EncryptedBinary));

        cmd.ExecuteNonQuery();
    }

现在是问题所在。在数据库中添加两个文件后,我尝试添加的其他文件是System.DBNull,但我不知道为什么。在添加第二个文件之后,我添加了下一个文件,但没有任何反应(无错误等)。但是,当我尝试接收文件后,我得到的错误是它们是System.DBNull。

我怎么知道它们是System.DBNull? 我尝试从数据库检索每个文件(大对象),并添加了if语句byte []是否为空:if ((reader["fileContent"] != System.DBNull.Value) && (reader["encrypthedFileContent"] != System.DBNull.Value)) 。原来我是对的。我收到的唯一文件(大对象)是我首先添加的文件。 (因为它们没有保存为System.DBNull)

我在做什么错了?

0 个答案:

没有答案