Reputation: 2140
When an user is logging in I am doing this:
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 ????
}
I want to return the values which are read. But what do I need to fill instead of the ????
I was doing it with a List<>
and a foreach loop, but someone suggested me to do this!
Upvotes: 0
Views: 142
Reputation: 70529
The user variable is out of scope in the loop. You only expect one user, I would do this:
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;
Upvotes: 2