You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用OracleReader导出BLOB文件时DBNull无法转Byte[]异常如何解决

异常原因

你遇到的类型转换异常是因为部分行的DATEIBLOB字段在Oracle中存储为NULL,对应.NET读取时的类型是System.DBNull,无法直接强制转换为byte[],可以通过条件判断完全规避该异常。

具体实现方案

在读取DATEIBLOB字段前,先通过IsDBNull方法判断该字段是否为NULL,根据业务需求选择跳过该行、生成空文件或者记录异常日志即可。

修改后的代码示例

using (OracleCommand cmd = new OracleCommand(oracleBlobSqlString))
{
    cmd.CommandType = CommandType.Text;
    cmd.Connection = oraCon;

    OracleDataReader myReader = cmd.ExecuteReader();
    // 提前获取DATEIBLOB字段的索引,提升读取效率
    int blobColIndex = myReader.GetOrdinal("DATEIBLOB");
    while (myReader.Read())
    {
        //Pfad
        string sqlPath = myReader.GetString(1);
        string sqlFilename = myReader.GetString(0);

        byte[] byteArray;
        // 判断字段是否为NULL
        if (myReader.IsDBNull(blobColIndex))
        {
            // 此处可根据业务需求调整逻辑:
            // 方案1:跳过NULL值的行,可加日志记录
            logFile($"跳过NULL值记录,文件路径:{sqlPath},文件名:{sqlFilename}");
            continue;
            // 方案2:生成空文件,将byteArray赋值为空数组
            // byteArray = Array.Empty<byte>();
        }
        else
        {
            byteArray = (Byte[])myReader[blobColIndex];
        }

        // 路径拼接推荐用Path.Combine,避免斜杠重复或缺失问题
        string fullPath = Path.Combine(pPath, sqlPath, sqlFilename);
        using (FileStream fs = new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write))
        {
            fs.Write(byteArray, 0, byteArray.Length);
        }

        if (exportToken.IsCancellationRequested)
        {
            cancelToken = true;
            break; // 收到取消请求直接跳出循环,不用继续读取
        }
    }
    myReader.Close();
    logFile("Dateiblobs nach " + pPath + " exportiert");
}
额外优化点
  • 提前通过GetOrdinal获取字段索引,比每次通过字段名读取的效率更高
  • 用Path.Combine拼接路径,避免手动拼接斜杠导致的路径错误
  • 收到取消请求后加break直接跳出循环,减少不必要的资源消耗

内容的提问来源于stack exchange,提问作者user9715288

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:06:02