为什么这个 SQL 输出参数不能很好地发挥作用?
我有以下代码。当我使用断点时,我可以看到 ["@myID"].Value 是一个真实值,例如 2467。但是,我无法将其转换为 tryParse 的字符串。我尝试过使用“as string”,如下所示,我也尝试过 toString()。我的 stringID 保持为空,因此 tryParse 将 myID 值保留为零。我确信这是一个微不足道的语法问题,但我很困惑。我需要返回一个真实的ID,例如2467等。
public static int myMethod(string name)
{
Database myDB = DatabaseFactory.CreateDatabase("myDatabase");
DbCommand myCommand = myDB.GetStoredProcCommand("myStoredProc");
myDB.AddInParameter(myCommand, "@Name", DbType.String, name);
myDB.AddOutParameter(myCommand, "@myID", DbType.Int32, 4);
int myID = 0;
int test = myDB.ExecuteNonQuery(myCommand);
string stringID = myCommand.Parameters["@myID"].Value as string;
bool canParse = int.TryParse(stringID, out myID);
return myID;
}
I have the following code. When I use breakpoints, I can see that ["@myID"].Value is a real value, such as 2467. However, I'm not able to cast that as a string for my tryParse. I've tried using "as string" like below, and I've also tried toString(). My stringID remains null, so the tryParse leaves the myID value as a zero. I'm sure it's a trivial syntax issue, but I'm stumped. I need to return a real ID such as 2467, etc.
public static int myMethod(string name)
{
Database myDB = DatabaseFactory.CreateDatabase("myDatabase");
DbCommand myCommand = myDB.GetStoredProcCommand("myStoredProc");
myDB.AddInParameter(myCommand, "@Name", DbType.String, name);
myDB.AddOutParameter(myCommand, "@myID", DbType.Int32, 4);
int myID = 0;
int test = myDB.ExecuteNonQuery(myCommand);
string stringID = myCommand.Parameters["@myID"].Value as string;
bool canParse = int.TryParse(stringID, out myID);
return myID;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的猜测是演员阵容失败了。您将 OUT 参数声明为 INT,您也应该尝试将其读回 int:
而且我认为您不需要在下一行再次尝试解析它。
myCommand.Parameters["@myID"].Value
应该已包含该值。My guess is that the cast is failing. You are declaring the OUT param as INT, you should attempt to read it back as int as well:
And I don't think you need to attempt to parse it again on the next line.
myCommand.Parameters["@myID"].Value
should already contain the value.您也可以使用“Convert.ToInt32”函数
Also you can use "Convert.ToInt32" function