Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get int value from command in c#

Tags:

c#

sql

string sql = "Select UserId From User where UserName='Gheorghe'";


SqlCommand cmd=new SqlCommand(sql, connection);
cmd.ExecuteScalar(); //this statement return 0

but I want to get the id of user? how can I get it?

like image 981
Stack User Avatar asked Jul 29 '12 17:07

Stack User


2 Answers

You need the SqlDataReader.

SqlDataReader Provides a way of reading a forward-only stream of rows from a SQL Server database.

Sample

string sql = "Select UserId From User where UserName='Gheorghe'";

SqlCommand cmd=new SqlCommand(sql, connection);
SqlDataReader rd = cmd.ExecuteReader(); 
if (rd.HasRows) {
  rd.Read(); // read first row
  var userId = rd.GetInt32(0);
}

More Information

  • MSDN - SqlDataReader Class
like image 101
dknaack Avatar answered Sep 27 '22 21:09

dknaack


Simply cast the returned value:

int userId = (Int32)cmd.ExecuteScalar();

But be aware that ExecuteScalar will return null if your query returns an empty result set, and in that case the above code snippet will throw an InvalidCastException.

like image 38
Thomas C. G. de Vilhena Avatar answered Sep 27 '22 23:09

Thomas C. G. de Vilhena