Int32.TryParse()或(INT?)command.ExecuteScalar() [英] Int32.TryParse() or (int?)command.ExecuteScalar()

查看:221
本文介绍了Int32.TryParse()或(INT?)command.ExecuteScalar()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

和我不得不使用它在C#code整数。

哪种方式速度更快,占用内存更少?

 内部ID;
如果(Int32.TryParse(command.ExecuteScalar()。toString()方法,掉id))
{
  //使用ID
}
 

 诠释? ID =(INT?)command.ExecuteScalar();
如果(id.HasValue)
{
  //使用id.Value
}
 

 诠释? ID = command.ExecuteScalar()以int ?;
如果(id.HasValue)
{
  //使用id.Value
}
 

解决方案

这三个性能之间的差异聪明的可以忽略不计。瓶颈是从数据库中的数据转移到你的应用程序,而不是一个简单的铸件或方法调用。

我会跟去:

 诠释? ID =(INT?)command.ExecuteScalar();
如果(id.HasValue)
{
  //使用id.Value
}
 

早期失败,如果有一天人们改变命令返回一个字符串或日期,至少它会崩溃,你将不得不解决它的机会。

我也只是去用一个简单的 INT 铸造如果我一直期待的命令返回一个结果。

请注意,我一般是preFER返回一个出参数比做执行标,执行标感到脆弱(第一行中的第一列是一个返回值不坐适合我的约定)。

I have a SQL query which returns only one field - an ID of type INT.

And I have to use it as integer in C# code.

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
}

解决方案

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 IF I always expected the command to return a single result.

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).

这篇关于Int32.TryParse()或(INT?)command.ExecuteScalar()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆