从c#中的命令获取int值

string sql = "Select UserId From User where UserName='Gheorghe'"; SqlCommand cmd=new SqlCommand(sql, connection); cmd.ExecuteScalar(); //this statement return 0 

但我想获得用户的身份? 我怎么才能得到它?

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

更多信息

  • MSDN – SqlDataReader类
 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(); } } 

只需转换返回的值:

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

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