如何从sql server 2008获取列值?

时间:2013-09-08 18:05:20

标签: c# asp.net sql sql-server-2008

我的桌子有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 个答案:

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

答案 1 :(得分: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"]);

          }

   }

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:0)

试用此代码

SELECT count(*),userid,role FROM aspnet_Users where Username=@uname AND Password = @pwd Group by userid,role