0

我有一个有 5 列的表:

我写了这样的代码:

String SQLQuery = "SELECT count(*) FROM aspnet_Users where Username=@uname AND Password = @pwd";
    using(SqlConnection sqlConnection = new SqlConnection(strConnection))
    using(SqlCommand command = new SqlCommand(SQLQuery, sqlConnection))
    {
        sqlConnection.Open();
        command.Parameters.AddWithValue("@uname", Username);
        command.Parameters.AddWithValue("@pwd", Password);
        int result = Convert.ToInt32(command.ExecuteScalar());
        boolReturnValue = (result > 0);
    }

这里我需要一些额外的信息,如果上面的用户名和密码是正确的,我需要的是:用户 ID 和角色列数据

4

4 回答 4

2

为什么你不这样做呢?

string SQLQuery = "SELECT UserId FROM aspnet_Users where Username=@uname AND Password = @pwd";
[...]
object result = command.ExecuteScalar();
if (result == null)
{
    boolReturnValue = false;
}
else
{
    long userId = Convert.ToInt64(result);
    boolReturnValue = true;
}
于 2013-09-08T18:12:09.313 回答
1
String SQLQuery = "SELECT Top 1 UserId, role  FROM aspnet_Users where Username=@uname AND Password = @pwd";
    using(SqlConnection sqlConnection = new SqlConnection(strConnection))
    using(SqlCommand command = new SqlCommand(SQLQuery, sqlConnection))
    {
        sqlConnection.Open();
        command.Parameters.AddWithValue("@uname", Username);
        command.Parameters.AddWithValue("@pwd", Password);

         SqlDataReader Reader = null;
         if (sqlConnection.State == ConnectionState.Closed || sqlConnection.State == ConnectionState.Broken)
                    sqlConnection.Open();
            Reader = command.ExecuteReader();
           if (Reader.Read())
          {
            int UserId = Convert.ToInt32(Reader["UserId"]);
            string Role = Convert.ToString(Reader["role"]);

          }

   }
于 2013-09-08T18:28:50.337 回答
0

试试这个代码

SELECT count(*),userid,role FROM aspnet_Users where Username=@uname AND Password = @pwd Group by userid,role 
于 2013-09-09T02:03:10.700 回答
0

为什么不直接获取 UserId 而不是 Count(*),这样您的查询应该如下所示:

SELECT UserId FROM aspnet_Users where Username=@uname AND Password = @pwd

用户名应该是唯一的,因此您不应检索超过一行...如果您有多个相同的用户名和相同的密码,您可以添加前 1 个。

于 2013-09-08T18:09:49.673 回答