gpt4 book ai didi

c# - 如何在 Mysql Connector/NET 中省略对 SqlNullValueException 的检查

转载 作者:行者123 更新时间:2023-11-29 01:24:49 26 4
gpt4 key购买 nike

当从读取器读取数据时,我必须检查数据库中允许空值的每个参数是否抛出 NullValueException。特别是我必须使用单独的 try/catch 检查每个值,因为我仍然想解析第一个值为空的下一个值。在 C# 中,一些类有一个 tryParse(key, out value) 函数,成功时返回一个 bool 值,但我没有在 Connector/NET 中找到它。有什么办法可以缩短以下语句吗?

Product product;
try {
product = new Product(
reader.GetString("product_id"),
reader.GetDateTime("starttime")
);
try {
product.EndTime = reader.GetDateTime("endtime");
} catch (System.Data.SqlTypes.SqlNullValueException) { }
try {
product.Description = reader.GetString("description");
} catch (System.Data.SqlTypes.SqlNullValueException) { }
try {
product.Type = reader.GetString("type");
} catch (System.Data.SqlTypes.SqlNullValueException) { }
} catch (MySqlException ex) {
throw ex;
} catch (Exception ex) {
throw ex;
}

最佳答案

我通常在 SqlDataReader 中使用这种模式,我想它应该与 MySQL Connector/Net 相同。

product.EndTime = reader["endtime"] as DateTime? ?? DateTime.MinValue;
product.Description = reader["description"] as string;
product.Type = reader["type"] as string;

关于c# - 如何在 Mysql Connector/NET 中省略对 SqlNullValueException 的检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4800731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com