17

我有一个 SQL 查询,它只返回一个字段 - 一个 INT 类型的 ID。

而且我必须在 C# 代码中将其用作整数。

哪种方式更快并且使用更少的内存?

int id;
if(Int32.TryParse(command.ExecuteScalar().ToString(), out id))
{
  // use id
}

或者

int? id = (int?)command.ExecuteScalar();
if(id.HasValue)
{
  // use id.Value
}

或者

int? id = command.ExecuteScalar() as int?;
if(id.HasValue)
{
  // use id.Value
}
4

7 回答 7

23

三个性能方面的差异可以忽略不计。瓶颈是将数据从数据库移动到您的应用程序,而不是微不足道的强制转换或方法调用。

我会去:

int? id = (int?)command.ExecuteScalar();
if(id.HasValue)
{
  // use id.Value
}

更早地失败了,如果有一天人们将命令更改为返回字符串或日期,至少它会崩溃,您将有机会修复它。

如果我一直希望该命令返回单个结果,我也会使用简单的int强制转换。

注意,我通常更喜欢返回一个输出参数而不是执行标量,执行标量感觉很脆弱(第一行中的第一列是返回值的约定不适合我)。

于 2009-07-23T22:57:58.983 回答
19

如果您希望该命令返回 null,则应记住数据库 null ( DBNull ) 与 .NET null 不同。那么,将 DBNull 转换为 int 呢?会失败。

我建议如下:

object result = command.ExecuteScalar();
int? id = (int?)(!Convert.IsDBNull(result) ? result : null);
于 2009-07-23T23:29:02.853 回答
5

如果上述方法都不起作用(尤其是对于与 MySQL 斗争的用户),为什么不尝试以下方法呢?

int id = Convert.ToInt32(cmd.ExecuteScalar().ToString());
于 2012-07-15T14:11:21.560 回答
3
int Result = int.Parse(Command.ExecuteScalar().ToString());

将在 C# 中工作。

于 2012-09-04T16:44:43.713 回答
2

后者。 Convert.ToInt32()也是一种选择。

于 2009-07-23T22:52:03.507 回答
1

使用 id.HasValue 获得最大的 Nullable Type 酷因子!

于 2009-07-23T22:59:50.587 回答
-2
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") ;
}
于 2014-08-16T05:52:07.467 回答