从数据库查询中返回一些值

时间:2013-07-20 00:09:33

标签: c# asp.net mysql sql class

当用户登录时,我这样做:

public static User GetUser(string nickname, string password)
{
    try
    {
        connection.Open();
        string sql = "SELECT * FROM User WHERE Nickname = @nickname AND Password = @password";
        command = new MySqlCommand(sql, connection);
        command.Parameters.Add(new MySqlParameter("@nickname", nickname));
        command.Parameters.Add(new MySqlParameter("@password", password));
        reader = command.ExecuteReader();

        while (reader.Read())
        {
            int UserID = Convert.ToInt32(reader["UserID"]);
            int IsAdmin = Convert.ToInt32(reader["IsAdmin"]);
            int IsActivated = Convert.ToInt32(reader["IsActivated"]);
            string Nickname = reader["Nickname"].ToString();
            string FirstName = reader["FirstName"].ToString();
            string LastName = reader["LastName"].ToString();
            string Email = reader["Email"].ToString();
            string Password = reader["Password"].ToString();
            string DateRegistered = reader["DateRegistered"].ToString();

            User user = new User(UserID, IsAdmin, IsActivated, null, Nickname, FirstName, LastName, Email, Password, DateRegistered);
        }
    }
    catch
    {
    }
    finally
    {
        connection.Close();
    }
    return ????
}

我想返回读取的值。但是我需要填写什么而不是????

我是用List<>和foreach循环做的,但有人建议我这样做!

1 个答案:

答案 0 :(得分:2)

用户变量超出了循环范围。你只期望一个用户,我会这样做:

User user=null;
if (reader.Read())
{
        int UserID = Convert.ToInt32(reader["UserID"]);
        int IsAdmin = Convert.ToInt32(reader["IsAdmin"]);
        int IsActivated = Convert.ToInt32(reader["IsActivated"]);
        string Nickname = reader["Nickname"].ToString();
        string FirstName = reader["FirstName"].ToString();
        string LastName = reader["LastName"].ToString();
        string Email = reader["Email"].ToString();
        string Password = reader["Password"].ToString();
        string DateRegistered = reader["DateRegistered"].ToString();

        user = new User(UserID, IsAdmin, IsActivated, null, Nickname, FirstName, 
}
else 
{

  // handle error no user
}

if (reader.Read())
{
   // handle more than one user error
}

// other stuff close connect and reader etc.

return user;