如何在 Mysql Connector/NET 中省略对 SqlNullValueException 的检查
从读取器读取数据时,我必须检查数据库中允许空值的每个参数是否抛出 NullValueException。特别是我必须使用单独的 try/catch 检查每个值,因为我仍然想解析第一个值为空的下一个值。在 C# 中,某些类有一个 tryParse(key, out value) 函数,成功时返回一个布尔值,但我没有在 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;
}
When reading data from the reader I have to check each parameter that allows for null values in the database whether it is threw a NullValueException. Especially I have to check each value with a separate try/catch because I still want to parse the next value it the first one was null. In C# some classes have a tryParse(key, out value) function, which returns a boolean on success, but I didn't find it for Connector/NET. Is there any way to shorten the following statements?
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常将这种模式与 SqlDataReader 一起使用,我想它应该与 MySQL Connector/Net 相同。
I usually use this pattern with SqlDataReader, I imagine it should be the same with MySQL Connector/Net.
MySqlDataReader 有一个方法“IsDBNull(int i)”,可用于检查空值。
The MySqlDataReader has a method "IsDBNull(int i)" that you can use to check for null values.