与数据库值进行比较

时间:2013-06-11 00:56:33

标签: c# asp.net sql-server

我要做的是获取当前登录用户的用户名并将其与包含用户的数据库进行比较,还包括Active标记和Admin标记。我想比较tbl_Person表中当前登录的用户和表中各自的用户,看看他们是否被标记为Active和Admin。如果两者都为真,则可以访问管理员页面。到目前为止,我有以下哪些不起作用。其中一些我知道为什么,有些我不知道。我认为我走在正确的轨道上,据说我确信我没有正确地做到这一点。我知道你使用ExecuteScalar()在查询字符串中返回OUTPUT,但无法使其工作。另一个明显的问题是,当用户名是字符串并且active和admin标志是Bools时,我试图返回整数。我知道我只有活跃的时刻。在添加其他内容之前,我试图让它工作。

我用ExecuteScalar读到了,你可以解析并转换ToString,但这不起作用,我发现这可能不是正确的事情,但我真的不确定。

我有一些不同的错误。当我尝试执行OUTPUT时输入错误,列无效。使用OUTPUT我尝试只是输出,因为我知道在插入后返回时,你会执行inserted.name。我尝试将selected.name作为预感,但这不起作用。

我在想,如果我提取信息,连接它们然后进行比较,这会做我想要的,但我愿意接受其他建议。感谢。

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HSEProjRegConnectionString1"].ConnectionString);
conn.Open();
SqlCommand sqlUserName = new SqlCommand("SELECT [username] FROM [tbl_Person]", conn);
SqlCommand sqlActive = new SqlCommand("SELECT [active] FROM [tbl_Person]", conn);
int result1 = ((int)sqlUserName.ExecuteScalar());
int result2 = ((int)sqlActive.ExecuteScalar());

string userInfo = result1 + "." +result2;
string userName = userName + "." +result2;

if (userInfo == userName)
{
    Woo, you have access.
}
else
{
    Sorry, but no.
}

查询也不是最终的。一旦它工作,我会将其更改为参数化查询。

1 个答案:

答案 0 :(得分:1)

好的,请考虑以下代码:

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HSEProjRegConnectionString1"].ConnectionString))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT [active] FROM [tbl_Person] WHERE username = @username", conn))
    {
        // since we can literally filter the results, if something comes back
        // we know they are registered
        cmd.Parameters.AddWithValue("@username", userName);

        var res = cmd.ExecuteScalar();
        bool registeredAndActive = (bool)res;

        // unless of course `[active]` is an INT -then do this
        bool registeredAndActive = (int)res == 1 ? true : false;

        // but really -set [active] up as a BIT if it's not **and**
        // please make it non-nullable :D
    }
}

我很确定它会做你想要的。但它也向您展示了一些最佳实践:

  1. 利用所有using个对象的IDisposable语句。
  2. 尽可能多地过滤查询,只进行一次往返。
相关问题