0

我试图让我的应用程序检查我的 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 + "'");
}
4

2 回答 2

3

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

例如,您的管理员可能如下所示:

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;
  }

这至少应该让你朝着正确的方向开始。

于 2013-01-16T22:06:14.213 回答
2

撇开以前的海报所说的一切,我都同意,所提供的代码将不起作用,因为在那个 while 循环期间,您正在做的是用用户信息填充列表框或某种下拉列表(部门为Display 和 Userid 作为值)。

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

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

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

哎呀......我知道在你的具体情况下你不接受用户输入,但迟早你会......

希望这可以帮助。

于 2013-01-17T01:10:02.837 回答