无法将类型为“System.DBNull”的对象强制转换为类型“System.String”.错误

本文关键字:System 类型 错误 String 转换 DBNull 对象 | 更新日期: 2023-09-27 18:33:46

我一直收到此错误,因为该记录的供应商ID为空。我已经看到这个问题已经被问了几次,似乎我应该在转换它并将其输入 dbtable 之前检查一下是否为 null,但我不确定该怎么做。

public static PartOrder findPartOrder(string orderNo)
    {
        PartOrder aPartOrder = new PartOrder();
        OleDbDataAdapter myAdapter = new OleDbDataAdapter();
        if (aConnection.State == ConnectionState.Closed)
            aConnection.Open();
        OleDbCommand cmd = aConnection.CreateCommand();
        OleDbDataReader dbReader = null;
        cmd.CommandText = "SELECT * FROM PartOrder WHERE OrderNo = '" + orderNo + "'";
        dbReader = cmd.ExecuteReader();
        while (dbReader.Read())
        {
            aPartOrder.OrderNo = (string)dbReader.GetValue(0);
            aPartOrder.Length = (string)dbReader.GetValue(1);
            aPartOrder.Finish = (string)dbReader.GetValue(2);
            aPartOrder.Cost = (string)dbReader.GetValue(3);
            aPartOrder.PartDrawingNo = (string)dbReader.GetValue(4);
            aPartOrder.VendorId = (string)dbReader.GetValue(5);
            aPartOrder.ShopId = (string)dbReader.GetValue(6);
            aPartOrder.Completed = (string)dbReader.GetValue(7);
        }
        dbReader.Close();
        return aPartOrder;
    }

同样,行"aPartOrder.VendorId = (string)dbReader.GetValue(5);"会出错,因为 VendorId 为空。

无法将类型为“System.DBNull”的对象强制转换为类型“System.String”.错误

对于此特定行,请尝试以下操作:

aPartOrder.VendorId = dbReader.GetValue(5)==DBNull?"":dbReader.GetValue(5).value;

最好是编写一个辅助函数:

private static string MyToString(object o)
{
    if(o == DBNull.Value || o == null) 
       return "";
    return o.ToString();
}

并使用它:

aPartOrder.VendorId = MyToString(dbReader.GetValue(5));

单行答案

aPartOrder.VendorId = dbReader.IsDBNull(5) ? "" :(string)dbReader.GetValue(5);

dbReader.GetValue(5).HasValue ? dbReader.GetValue(5).ToString() : String.Empty

使用OleDbDataReader.IsDBNull(ordinal)验证字段值。

if(!dbReader.IsDBNull(5))
  aPartOrder.VendorId = dbReader.GetString(5);

建议:始终使用参数/预编译的 sql 语句来防止 SQL 注入攻击。

cmd.CommandText = "SELECT * FROM PartOrder WHERE OrderNo = @OrderNo";
cmd.Parameters.Add("@OrderNo",System.Data.OleDb.OleDbType.VarChar,20).Value=orderNo;
dbReader = cmd.ExecuteReader();
相关文章: