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


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

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

4

3 回答 3

6

你需要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);
}

更多信息

于 2012-07-29T18:01:58.453 回答
3

只需转换返回值:

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

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

于 2012-07-29T18:02:31.680 回答
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();
    }
}
于 2012-07-29T18:04:09.203 回答