Get int value from command in C #

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 user id? how can i get it?

+4
source share
3 answers

You need SqlDataReader .

SqlDataReader Provides a way to read a direct stream of rows from a SQL Server database.

Example

 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); } 

Additional Information

+4
source

Just enter the return value:

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

But keep in mind that ExecuteScalar will return null if your query returns an empty result set, in which case the code snippet above will raise an InvalidCastException .

+2
source
 try with select TOP 1 and ExecuteScalar string sql = "Select TOP 1 UserId From User where UserName='Gheorghe'"; using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); using(SqlCommand cmd = new SqlCommand(sql, conn)) { var result = (Int32)cmd.ExecuteScalar(); } } 
+2
source

All Articles