首页 > 解决方案 > C#.Net & MySQL Database Login error how to fix

问题描述

Pro devs, I have a problem with my code in c#.net and I knew you can help me. the problem is in the Login code, every time I entered a value that is existed in the database it says "Username or password is incorrect" and when I entered a value that does not exist in the DB it says again "Username or password is incorrect" please help me thank you.

I have tried to edit the query and remove the open close in the asterisk but the output is the same.

public void checkLoginAccount()
    {
        frmMain frmLogin = new frmMain();
        con = new MySqlConnection();
        con.ConnectionString = "server=localhost;userid=root;password=alpine;port=3305;database=pos_db;pooling=false;SslMode=none";

        con.Open();
        string qry = "SELECT COUNT(*) FROM pos_db.tbllogin WHERE BINARY Username=@user AND BINARY Password=@pass";
        MySqlCommand cmd = new MySqlCommand(qry, con);
        cmd.Parameters.AddWithValue("@user", frmLogin.txtUsername.Text);
        cmd.Parameters.AddWithValue("@pass", frmLogin.txtPassword.Text);

        int count = Convert.ToInt32(cmd.ExecuteScalar());

        if (count != 0)
        {   
            MessageBox.Show("Welcome");
        }
        else
        {
            MessageBox.Show("Either username or password is incorrect!");
            return;
        }
        con.Close();
        con.Dispose();
    }

标签: c#

解决方案


您正在函数中创建一个新的表单实例:

 frmMain frmLogin = new frmMain();

所以这里的用户名和密码总是空的:

cmd.Parameters.AddWithValue("@user", frmLogin.txtUsername.Text);
cmd.Parameters.AddWithValue("@pass", frmLogin.txtPassword.Text);

您需要使用正确的表单实例。


推荐阅读