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

后端 未结 7 2232
既然无缘
既然无缘 2020-12-18 20:14

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?

7条回答
  •  庸人自扰
    2020-12-18 20:28

    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.

    I'd suggest the following:

    object result = command.ExecuteScalar();
    int? id = (int?)(!Convert.IsDBNull(result) ? result : null);
    

提交回复
热议问题