登录页面到mysql
本文关键字:mysql 登录 | 更新日期: 2023-09-27 18:03:11
我做了一个登录页面,检查数据库的用户名和密码但它只是允许任何用户名和密码它不拒绝他们不知道为什么我是新手,下面是表单,我在数据库中输入了user_name和password的数据所以这是错误的不是代码中一定有问题但是当我关闭程序时它也显示密码不正确这很奇怪只有当我点击关闭程序时它才显示这很奇怪
namespace LoginApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
PassTextBox.PasswordChar = '•';
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string MyConnection = "datasource=localhost;port=3306;username=user;password=pass";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand("select * from etool.login where user_name='" + this.UserTextBox.Text + "' and password='" + this.PassTextBox.Text + "' ;", MyConn);
MySqlDataReader MyReader;
MyConn.Open();
MyReader = MyCommand.ExecuteReader();
int count = 0;
while (MyReader.Read())
{
Console.WriteLine(MyReader[count]);
count++;
}
MessageBox.Show("Username and password is correct");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
if (count == 1)
{
}
else if (count > 1)
{
MessageBox.Show("Duplicate Username and passwor.'nAccess denied.");
}
else
{
MessageBox.Show("Username and password is incorrect.'nPleas try again.");
}
MyConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
首先,你真的应该使用参数,而不是像你那样用变量构造命令。
第二,你不应该在这里输入你的用户而传递给root。
第三,您将始终显示"用户名和密码是正确的"消息,因为没有什么可以阻止这种情况发生。
实际上,你的代码是这样的:
while (MyReader.Read())
{
Console.WriteLine(MyReader[count]);
count++;
}
//This block of code will ALWAYS be executed,
//no matter the value of count.
MessageBox.Show("Username and password is correct");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
//This IF block is doing nothing.
if (count == 1)
{
}
可以看到,只有在计数器的值为1的情况下才应该执行的代码无论如何都要执行。
你需要把只在count等于1 时才必须执行的那部分代码放在里面检查count是否等于1的if:
if (count == 1)
{
MessageBox.Show("Username and password is correct");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
}