如何处理字节[]中的空值
本文关键字:空值 字节 何处理 处理 | 更新日期: 2023-09-27 18:21:21
我在数据库表的Image
列中有二进制图像,但在Image
列中有一些null
值。所以抛出了一个异常,
byte[]数据=(byte[])ds.Tables[0]。Rows[0][0]`,因为为null。
如何处理?
异常消息,
无法将"System.DBNull"类型的对象强制转换为"System.Byte[]"类型。
我的代码,
using (var sqlConn = new SqlConnection(connstr))
{
sqlConn.Open();
ds = new DataSet();
SqlDataAdapter sqa = new SqlDataAdapter("Select Image from Templates where Shoe='" + selectedShoe + "'", sqlConn);
sqa.Fill(ds);
//i got error here
byte[] data = (byte[])ds.Tables[0].Rows[0][0];
.....
在尝试强制转换之前,您需要特别检查该列中的DBNull
:
byte[] data = null;
if (!ds.Tables[0].Rows[0].IsNull(0))
data = (byte[])ds.Tables[0].Rows[0][0];
请注意,如果有问题的列实际上不包含字节数组,则此操作将失败,并出现相同类型的异常。
在SQL查询中处理null对我来说很有效。如果Image列为null,ISNULL()函数将返回下一个值(本例中为0)。
SqlDataAdapter sqa = new SqlDataAdapter("SELECT ISNULL([Image],0) AS Image FROM Templates where Shoe='" + selectedShoe + "'", sqlConn);