Int32.TryParse() or (int?)command.ExecuteScalar()

2019-01-26 04:29发布

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
}

7条回答
贼婆χ
2楼-- · 2019-01-26 04:51

If none of the above works (especially for users who are battling with MySQL) why don't you try the following?

int id = Convert.ToInt32(cmd.ExecuteScalar().ToString());
查看更多
登录 后发表回答