0

我几天前发布了这个如何在插入gridview之前知道一行的值? 我得到了这个答案

SqlCommand cmdEvent = new SqlCommand("SELECT COUNT(date) FROM patients WHERE date= '2012/02/23'", yourSqlConnection);
object myCount;
if (yourSqlConnection.State == ConnectionState.Closed){ yourSqlConnection.Open(); }
myCount = cmdEvent.ExecuteScalar();
if (yourSqlConnection.State == ConnectionState.Open){ yourSqlConnection.Close(); }

if (myCount != null)
{
  if ((int)myCount >= 10)
  {
    // Logic here e.g myLabel.Text = "You have reached your maximum of 10 visits!";
    return;
  }
}

但是现在我在插入之前不需要一行的值,相反,我需要知道 2 行的值,我不知道该怎么做。我正在尝试登录,我需要用户的 id 来使会话唯一,但我还需要验证该查询是否返回 true,并且我按照以下方式进行操作:

comando = new SqlCommand("SELECT user_name FROM login WHERE user_name=@user AND pass=@pass", conexion);
comando.Parameters.AddWithValue("@pass", Upass);
comando.Parameters.AddWithValue("@user", user);
object check_coincidence = comando.ExecuteScalar();

if ((string)check_coincidence == user)
{
     Session["USER"] = check_coincidence;
     Response.Redirect("someURL")
}

但我不知道如何获取用户 ID 以使会话唯一,我的意思是,将该值作为新会话。

4

1 回答 1

1

要从查询中获得更多结果,您必须使用 SqlReader。

comando = new SqlCommand("SELECT user_name, user_id FROM login WHERE user_name=@user AND pass=@pass", conexion);
comando.Parameters.AddWithValue("@pass", Upass);
comando.Parameters.AddWithValue("@user", user);

 SqlDataReader reader = commando.ExecuteReader();
        while (reader.Read())
        {
            var userName = Convert.ToString(reader["user_name"]);
            var userId = Convert.ToInt32(reader["user_id"]); 
        }

我建议遵循一些关于此的教程,这将有助于理解 Sql 类。例如检查这个: http: //csharp-station.com/Tutorials/AdoDotNet/Lesson03.aspx

于 2013-02-25T21:56:29.120 回答