[英]How to avoid exception in case if string returned from database is null or empty?
I have a business rules where string needs to be converted to Base64. 我有一条需要将字符串转换为Base64的业务规则。
The method that execute stored procedure may return a valid string or null string, for example: 执行存储过程的方法可能返回有效字符串或空字符串,例如:
public static string GetReturnString()
{
...
try
{
con.Open();
myString = cmd.ExecuteScalar().ToString();
return myString;
}
catch{Exception ex)
{
InsertErrorInDB(....);
return null;
}
finally
{
con.Close();
cmd.Close();
}
}
Then, I have a method that calls above method: 然后,我有一个调用上述方法的方法:
public string GetCode()
{
string myString = GetReturnString();
ConvertToBase64String(myString); // this method will have an exception if myString is null
.....
}
If I add a check: 如果我添加支票:
if(myString != null || myString.Length !=0)
{
ConvertToBase64String(myString);
}
, I will not have an error, but how to make sure that myString will never be null, so this code will always execute? ,我不会出错,但是如何确保myString永远不会为null,因此该代码将始终执行?
What can I write in case if myString does not pass validation condition and is in fact null? 万一myString没有通过验证条件并且实际上为null,我该怎么写?
Can I have another attempt to retrieve it from database? 我可以再次尝试从数据库中检索它吗? Is there any other ways to accomplish that? 还有其他方法可以做到吗?
Thank you 谢谢
DBNull.ToString()
already returns String.Empty()
. DBNull.ToString()
已经返回String.Empty()
。 You can do the same thing in your exception handler: 您可以在异常处理程序中执行相同的操作:
public static string GetReturnString()
{
...
try
{
con.Open();
return cmd.ExecuteScalar().ToString();
}
catch{Exception ex)
{
InsertErrorInDB(....);
return string.Empty;
}
finally
{
con.Close();
cmd.Close();
}
}
This is least simplifies your test: 这至少可以简化您的测试:
if(myString != string.Empty)
{
myString = ConvertToBase64String(myString);
}
Also notice that I had to assign back to the original. 另请注意,我必须分配回原始文件。 If you don't do that, you'll throw away the result of the function call. 如果不这样做,则会丢弃函数调用的结果。
That's about as close as I can get for you question based on what was provided. 根据提供的内容,这与我能为您提出的问题差不多。 For rest of it, we'd need a lot more context, and there are as many ways to handle this as there are programmers in the world. 对于其余部分,我们需要更多的上下文,并且与世界上的程序员一样,有许多方法可以处理此问题。
While I'm here, let me add that re-using the same connection object, as you seem to be doing with the con
variable, is poor practice for ADO.Net. 当我在这里时,让我补充一点,重新使用同一个连接对象,就像您对con
变量所做的那样,对于ADO.Net来说是不好的做法。 You are really better off creating a new connection object for most every call to the database, and instead just re-use the same connection string. 最好为大多数对数据库的每次调用创建一个新的连接对象,而只重用相同的连接字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.