在定义类的While之外使用类

本文关键字:While 定义 | 更新日期: 2023-09-27 17:53:55

我试图让我的应用程序检查我的SQL数据库中的Admins表,然后获得当前用户所属部门的名称。之后,我想检查另一个表,只选择属于该部门的新闻项。

下面显示了我是如何处理它的,但是问题在于在While循环之外使用mydepartment变量(在第二个SQL查询中使用)。

除了那个,其他都可以。如有任何帮助,不胜感激。

public string username = System.Web.HttpContext.Current.User.Identity.Name.Split('''')[1];
public string mydepartment;
protected void Page_Load(object sender, EventArgs e)
{
    lblUser.Text = username.ToString();
    SqlConnection myConnection = new SqlConnection();
    myConnection.ConnectionString = @"Data Source=.'SQLEXPRESS;AttachDbFileName=|DataDirectory|'Database1.mdf;Integrated Security=True;User Instance=True";
    myConnection.Open();
    string selectretrieveSQL = ("SELECT * FROM Admins WHERE userid = '" + username.ToString() + "'");
    SqlCommand retrieveinfocmd = new SqlCommand(selectretrieveSQL, myConnection);
    SqlDataReader reader = retrieveinfocmd.ExecuteReader();
    while (reader.Read())
    {
        ListItem newItem = new ListItem();
        newItem.Text = reader["Department"].ToString();
        newItem.Value = reader["userid"].ToString();
        UserIds.Items.Add(newItem);
        mydepartment = reader["Department"].ToString();
        mydepartmentlbl.Text = reader["Department"].ToString();
    }
    reader.Close();
    string selectNewsSQL = ("SELECT * FROM NewsItems WHERE Department = '" + mydepartment + "'");
}

在定义类的While之外使用类

首先,我强烈建议您创建一些类来保存数据库对象的属性。

例如,也许你的Admin看起来像这样:
public class Admin
{
  public string Username { get; set; }
  public string Department { get; set; }
  // .. More properties here
}

接下来,您应该创建一些方法来为您完成这些繁琐的工作。我将从数据库初始化开始:

static SqlConnection InitializeDatabase(string connectionString)
{
  var connection = new SqlConnection(connectionString);
  connection.Open();
  return connection;
}

也许你有一个方法可以得到合适的Admin:

static IEnumerable<Admin> GetAdminsByUsername(SqlConnection connection, 
                                              string username)
{
  var adminList = new List<Admin>();
  // You really should be using stored procedures here instead...
  var query = @"SELECT * FROM Admins WHERE Username = @Username";
  using (var command = new SqlCommand(query, connection))
  {
    command.Parameters.AddWithValue("@Username", username);
    using (var reader = command.ExecuteReader())
    {
      while (reader.Read())
      {
        var adminUsername = reader["Username"].ToString();
        var adminDepartment = reader["Department"].ToString();
        var admin = new Admin
        {
          Username = adminUsername,
          Department = adminDepartment
        };
        adminList.Add(admin);
      }
      reader.Close();
      return adminList;
    }
  }
}

那么你的Page.Load可能看起来像这样:

protected void Page_Load(object sender, EventArgs e)
{
  var connectionString = @"Data Source=.'SQLEXPRESS;AttachDbFileName=|DataDirectory|'Database1.mdf;Integrated Security=True;User Instance=True";
  using(var connection = InitializeDatabase(connectionString))
  {
    var admin = GetAdminsByUsername(connection, username).FirstOrDefault();
    if(admin == null)
    {
      // No admin was found, do something here.
      return;
    }
    var newItem = new ListItem();
    newItem.Text = admin.Department.
    newItem.Value = admin.Username;
    // Keep your controls named consistently, don't use shorthands
    // since you already have IntelliSense to auto-complete them for you
    usernameLabel.Text = admin.Username;
    departmentLabel.Text = admin.Department;
  }

这至少能让你在正确的方向开始。

抛开前面的海报所说的一切,我都同意,所呈现的代码将不起作用,因为在while循环期间,您正在做的是填充一个列表框或下拉列表框,其中包含某种用户信息(Department作为显示,Userid作为值)。

如果您希望能够基于Department获取更多信息,则需要处理该列表框或select的SelectedIndexChanged事件(或类似事件),获取当前选定的文本值并,然后创建第二个查询并执行它。

然而

;请遵循前面海报的建议,你不必使用存储过程,但你确实应该在查询中使用参数。想象一下,如果某个讨厌的人设法传递UserID l33t';drop table Admins,会发生什么。您的页面将执行以下命令:

SELECT * FROM Admins WHERE userid = 'l33t';drop table Admins;

哦…我知道在你的特殊情况下,你不接受用户输入,但迟早你会…