从c#中的命令获取int值

时间:2012-07-29 17:58:25

标签: c# sql

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


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

但我想获得用户的ID? 我怎么能得到它?

3 个答案:

答案 0 :(得分:4)

您需要SqlDataReader

  

SqlDataReader 提供从SQL Server数据库中读取仅向前行的方法。

示例

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

更多信息

答案 1 :(得分:2)

只需转换返回的值:

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

但请注意,如果您的查询返回空结果集, ExecuteScalar 将返回 null ,在这种情况下,上面的代码段会抛出InvalidCastException

答案 2 :(得分:2)

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