从数据库查询中返回一些值
本文关键字:返回 数据库 查询 | 更新日期: 2023-09-27 18:24:11
当用户登录时,我会执行以下操作:
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循环来做,但有人建议我这样做!
用户变量超出了循环的范围。你只需要一个用户,我会这样做:
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;