我在输入用户名和密码与数据库中指定用户的用户名和密码进行比较时遇到问题。我相信所有代码都是正确的但是当我点击登录按钮时,没有任何反应。请帮助,如果您需要任何其他信息,请咨询。
代码:
private void btnLogin_Click(object sender, EventArgs e)
{
int numerror = 0;
if (UsernameTextBox.Text == "")
{
numerror = numerror + 1;
}
if (PasswordTextBox.Text == "")
{
numerror = numerror + 1;
}
if (numerror == 1)
{
ErrorLabel.Text = "*1 required field is blank.";
}
else if (numerror == 2)
{
ErrorLabel.Text = "*2 required fields are blank";
}
else
{
string connectionString = "datasource=localhost;port=3306;username=*****;password=**********";
string select = "SELECT username, password FROM userinfo.users " +
"WHERE username = @username AND password = @password";
using (MySqlConnection Conn = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(select, Conn))
{
cmd.Parameters.AddWithValue("@username", UsernameTextBox.Text);
cmd.Parameters.AddWithValue("@password", PasswordTextBox.Text);
Conn.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
string username = reader.GetString(0);
string password = reader.GetString(1);
if (username == UsernameTextBox.Text)
{
string encodeduserinputpassword = EncodePassword(PasswordTextBox.Text);
if (password == encodeduserinputpassword)
{
AirSpace airspaceform = new AirSpace();
airspaceform.Show();
this.Hide();
}
else
{
CMessageBox("Login Error", "Incorrect username or password.");
}
}
else
{
CMessageBox("Login Error", "Incorrect username or password.");
}
}
}
Conn.Close();
}
}
}
}
答案 0 :(得分:0)
您正在使用EncodePassword
编码的密码,但您的选择查询正在进行直接匹配。
将您的选择更改为
SELECT username, password FROM userinfo.users
WHERE username = @username
并删除密码参数。
private void btnLogin_Click(object sender, EventArgs e)
{
int numerror = 0;
if (UsernameTextBox.Text == "")
{
ErrorLabel.Text = "*1 required field is blank.";
}
else if (PasswordTextBox.Text == "")
{
ErrorLabel.Text = "*2 required fields are blank";
}
else
{
string connectionString = "datasource=localhost;port=3306;username=*****;password=**********";
string select = "SELECT username, password FROM userinfo.users " +
"WHERE username = @username";
using (MySqlConnection Conn = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(select, Conn))
{
cmd.Parameters.AddWithValue("@username", UsernameTextBox.Text);
Conn.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
string username = reader.GetString(0);
string password = reader.GetString(1);
string encodeduserinputpassword = EncodePassword(PasswordTextBox.Text);
if (password == encodeduserinputpassword)
{
AirSpace airspaceform = new AirSpace();
airspaceform.Show();
this.Hide();
}
else
{
CMessageBox("Login Error", "Incorrect username or password.");
}
}
else
{
CMessageBox("Login Error", "Incorrect username or password.");
}
}
Conn.Close();
}
}
}
}