string name = textBox1.Text;
            string pwd = textBox2.Text;
            string sqlStr = @"Data Source=lenovo-e0bed844;Initial Catalog=book;Uid=qq;Pwd=123";
            using (SqlConnection conn = new SqlConnection(sqlStr))
            {
                string sql = "select Upwd from [user1] where Uname=@name";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    
                    cmd.Parameters.Add(new SqlParameter("@name", name));
                    conn.Open();
                    using (SqlDataReader sr = cmd.ExecuteReader())
                    {
                        if (sr.Read())
                        {
                           
                            string pwd1 = sr["Upwd"].ToString();
                            //MessageBox.Show(pwd1);
                            if (pwd == pwd1)
                            {
                                MessageBox.Show("登录成功");
                            }
                            else
                            {                                MessageBox.Show("密码错误");
                            }
                        }
                        else
                        {
                            MessageBox.Show("用户名不存在");
                        }
                    
                    }
                }
            }
刚才问题找到了,现在又有了新问题
就是我的密码对了还是提示错误
什么原因  还有 请解释一下SqlDataReader.Read() 的作用

解决方案 »

  1.   

    数据库的密码字段可能用的是char型,要改成varchar型,char型长度不够会自动填充空格的,这样就和你输入的不相等了。Read方法向下读取一条记录,如果读取得到,返回true;否则返回false。
      

  2.   

    请问 我在用Read方法的时候如果不循环的话,我知道刚开始指向的是第一条数据之前,假如我输入的账户是很靠后的,我不循环的情况下,能登录成功吗
      

  3.   

    sql语句的where条件限制了无论循环与否都只能Read到一条记录,所以没问题。前提是where条件是正确的。