string sql = "Select UserId From User where UserName='Gheorghe'"; SqlCommand cmd=new SqlCommand(sql, connection); cmd.ExecuteScalar(); //this statement return 0
但我想获取用户ID?我怎么才能得到它?
您需要SqlDataReader。
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); }