C# Int32.TryParse() 或 (int?)command.ExecuteScalar()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1174930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Int32.TryParse() or (int?)command.ExecuteScalar()
提问by abatishchev
I have a SQL query which returns only one field - an ID of type INT.
我有一个只返回一个字段的 SQL 查询 - 一个 INT 类型的 ID。
And I have to use it as integer in C# code.
我必须在 C# 代码中将它用作整数。
Which way is faster and uses less memory?
哪种方式更快并且使用更少的内存?
int id;
if(Int32.TryParse(command.ExecuteScalar().ToString(), out id))
{
// use id
}
or
或者
int? id = (int?)command.ExecuteScalar();
if(id.HasValue)
{
// use id.Value
}
or
或者
int? id = command.ExecuteScalar() as int?;
if(id.HasValue)
{
// use id.Value
}
采纳答案by Sam Saffron
The difference between the three performance wise is negligible. The bottleneck is moving the data from the DB to your app, not a trivial cast or method call.
三种性能之间的差异可以忽略不计。瓶颈是将数据从数据库移动到您的应用程序,而不是简单的转换或方法调用。
I would go with:
我会去:
int? id = (int?)command.ExecuteScalar();
if(id.HasValue)
{
// use id.Value
}
It fails earlier, if one day people change the command to return a string or a date, at least it will crash and you will have a chance to fix it.
它更早失败,如果有一天人们更改命令以返回字符串或日期,至少它会崩溃并且您将有机会修复它。
I would also just go with a simple int
cast IFI always expected the command to return a single result.
如果我总是希望命令返回单个结果,我也只会使用简单的int
强制转换。
Note, I usually prefer returning an out param than doing the execute scalar, execute scalar feels fragile (the convention that the first column in the first row is a return value does not sit right for me).
注意,我通常更喜欢返回一个输出参数而不是执行标量,执行标量感觉很脆弱(第一行中的第一列是返回值的约定不适合我)。
回答by Joel Coehoorn
The latter. Convert.ToInt32()
is also an option.
后者。 Convert.ToInt32()
也是一种选择。
回答by xyz
Use id.HasValue for maximum Nullable Type cool-factor!
使用 id.HasValue 以获得最大的 Nullable Type 酷因素!
回答by VladV
If you expect the command to return null, you should keep in mind that database null (DBNull) is not the same as .NET null. So, conversion of DBNull to int? would fail.
如果您希望命令返回 null,则应记住数据库 null ( DBNull) 与 .NET null 不同。那么,DBNull 到 int 的转换?会失败。
I'd suggest the following:
我建议如下:
object result = command.ExecuteScalar();
int? id = (int?)(!Convert.IsDBNull(result) ? result : null);
回答by hungrycoder
If none of the above works (especially for users who are battling with MySQL) why don't you try the following?
如果以上都不起作用(特别是对于与 MySQL 作斗争的用户),为什么不尝试以下操作?
int id = Convert.ToInt32(cmd.ExecuteScalar().ToString());
回答by Sin
int Result = int.Parse(Command.ExecuteScalar().ToString());
will work in C#.
将在 C# 中工作。
回答by legc
if ((Int32)cmd.ExecuteScalar () ** 1) //en esta parece qu esta el error pero no lo veo
{
Response.Redirect("Default.aspx");
}
else
{
Response.Redirect("error.htm") ;
}