Sunday, February 12, 2012

Best way to get an INT from SQL

Is there a better way to do this?

int i;
myreader SqlDataReader;
...
try
{
...
if(myreader.Read())
{
i = myreader.GetInt16(0);
}
myreader.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
myreader = null;
}
return i;
If the query is just returning a single value (one row, one column) then it's slightly easier to use:

int i = 0;
Connection.Open();
try{
i = (int)cm.ExecuteScalar();
}
catch (Exception ex){
// etc
}
finally{
Connection.Close();
}

No comments:

Post a Comment