使用class of outside定义它的位置

时间:2013-01-16 21:12:00

标签: c# asp.net sql scope datareader

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

2 个答案:

答案 0 :(得分: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;
  }

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

答案 1 :(得分:2)

除了之前海报所说的所有内容,我同意的所有内容,所提供的代码都不会起作用,因为在那个while循环中,你正在做的是用一个用户信息填充列表框或某种下拉列表(显示部门和用户ID作为值)。

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

然而;请按照以前海报的建议,你不必使用存储过程,但你真的应该在查询中使用参数。想象一下如果一个讨厌的人设法传递 l33t&#39 ;; drop table Admins 的UserID会发生什么。然后您的页面将执行此操作:

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

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

希望这有帮助。