0

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

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循环来做的,但是有人建议我这样做!

4

1 回答 1

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;
于 2013-07-20T00:16:27.410 回答