简体   繁体   中英

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?

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM