Stack User
Stack User

Reputation: 1398

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

Upvotes: 6

Views: 23303

Answers (3)

Thomas C. G. de Vilhena
Thomas C. G. de Vilhena

Reputation: 14595

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.

Upvotes: 4

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28990

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

Upvotes: 2

dknaack
dknaack

Reputation: 60506

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

Upvotes: 7

Related Questions