您好我正在寻找一种方法来验证我添加到SqlCommand
作为参数的字符串是否正确。
这是我的代码:
string wrongType = "This is not a date";
command.Parameters.Add("@Date", SqlDbType.DateTime).Value = wrongType;
有没有办法检查wrongType
是否可以转换为SqlDbType.DateTime
?
答案 0 :(得分:1)
您可以使用DateTime.TryParse
:
string wrongType = "This is not a date";
DateTime rightTyped;
if(DateTime.TryParse(wrongType, out rightTyped))
{
command.Parameters.Add("@Date", SqlDbType.DateTime).Value = rightTyped;
}
答案 1 :(得分:1)
如果您收到用户输入,则必须验证输入。
试试这个:
string wrongType = "This is not a date";
DateTime date;
if(DateTime.TryParse(wrongType, out date))
{
// staff when string converted
}
答案 2 :(得分:1)
问题是第一行:
string wrongType = "This is not a date";
如果必须是日期,并且您的TSQL是针对某个日期的,那么...... 使用日期 :
DateTime rightType = ...
现在永远不会错。基本上,停止依赖字符串。其余代码仍然相似:
command.Parameters.Add("@Date", SqlDbType.DateTime).Value = rightType;
请注意,您可以使用DateTime.Parse
和DateTime.TryParse
从字符串输入到DateTime。