身份验证
我在做一个程序,连接上数据库了,用什么代码才能实现身份验证
我输入用户名,密码输入什么都进入用if怎么编写代码 急求 希望高手指点
------解决方案--------------------
登录伪代码
string sql = "select count(*) from table where username='zhangsan' and userpwd = 111";
SqlConnection
SqlCommand
int num = Convert.ToInt32(cmd.ExecuteScalar());
if(num>0)
{
MessageBox.Show("登录成功");
}
上面写法不建议,不好,建议使用如下写法
--登录常规做法:
1.根据用户名获取用户对象
2.用对象中的密码去和文本框输入的密码进行匹配
public class User
{
private int id=0;
private string userName=string.Empty;
private string userPassword=string.Empty;
....
....
....
public void SayHi()
{
Console.WriteLine("大家好,我叫{0},我的密码是{1}",userName,userPassword);
}
}
Main()
{
User u = null;
u.SayHi();
User user = new User();
user.SayHi(); //大家好,我的编号是0,我叫,密码是
User us = new User();
us.Id = 6;
us.UserName = "zhangsan";
us.UserPassword = "111";
us.SayHi(); //大家好,我的编号是6,我叫张三,密码是111
}
btnLogin_Click()
{
//获取用户名
string userName = txtUserName.Text.Trim();
//获取密码
string password = txtPassword.Text.Trim();
//根据用户名获取用户对象
User user = GetUserByUserName(userName);
//判断用户是否存在
if(user != null)
{
//存在该用户,判断密码是否正确
if(user.UserPassword == password)
{
//登录成功
}
else
{
MessageBox.Show("密码不正确");
}
}
else
{
MessageBox.Show("不存在该用户");
}
}
public User GetUserByUserName(string userName)
{
//声明用户对象
User user = null;
//拼接SQL
string sql = string.Format("select * from users where username='{0}'",userName);
//连接对象
SqlConnection con = ...;
con.Open();
//命令对象
SqlCommand cmd = ...;
//获取DataReader
SqlDataReader reader = cmd.ExecuteReader();
//读取行
if(reader.Read())
{
user = new User();
user.Id = Convert.ToInt32(reader["id"]);
user.UserName = reader["userName"].ToString();
user.userPassword = reader["userPassword"].ToString();
}
reader.Close();
con.Close();
//返回用户对象
return user;
}