使用数据库身份验证登录

本文关键字:登录 身份验证 数据库 | 更新日期: 2023-09-27 18:29:20

namespace Project
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        OleDbConnection MyCon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|'Project.accdb");
        public string user;
        string password;
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            user = textBox1.Text;
            char firstLetter = user[0];
            string password = textBox2.Text;
            MyCon.Open();
            string command = "Select Name from Login where userid=@userid AND password = @password";
            OleDbCommand cmd = new OleDbCommand(command, MyCon);
            cmd.Parameters.AddWithValue(@user, textBox1.Text);
            cmd.Parameters.AddWithValue(@password, textBox2.Text);
            OleDbDataReader dr = cmd.ExecuteReader();
            int id = cmd.Parameters[0].Value; // This line genrating error
          //  MessageBox.Show(user);
            if (firstLetter == 'E' )
            {
                if (dr.Read() == true )
                {
                    Window1 w1 = new Window1();
                    w1.textBox3.Text = user;
                    w1.textBox4.Text = dr[0].ToString();
                    w1.Show();
                    this.Close();
                    }
                    else
                    {
                        MessageBox.Show("NOt Login");    
                    }
                }

如何检索 id,然后将 id 和密码与用户登录相匹配?我的代码有问题。如果我给出了错误的id但正确的密码,那么用户可以登录。如果 id 和密码都错误,则不会发生这种情况;用户无法登录。.

使用数据库身份验证登录

你必须检查你的sqldatareader有行?

if (dr.HasRow){
 if (dr.Read())//Read Method Return a bool type
 {
  //Your Code
 }
}
cmd.Parameters.AddWithValue(@user, textBox1.Text);

此行应为

cmd.Parameters.AddWithValue(@userid, textBox1.Text);