首页 > 解决方案 > 执行登录时总是连接失败

问题描述

这是我第一次在 Visual Studio 2019 中使用 mysql。执行连接测试时,它是连接,但是当我创建简单的登录表单时,它总是显示连接失败,我无法找出问题,请帮助我...

public Form1()
    {
        InitializeComponent();
    }
    MySqlConnection conn = new MySqlConnection(@"Data Source=localhost;port=3306;Initial Catalog=Payroll_Management;User Id=root;password=;");
    private void label1_Click(object sender, EventArgs e)
    {

    }

    private void label3_Click(object sender, EventArgs e)
    {

    }

    private void textBox3_TextChanged(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        int i = 0;
        
        try
        {
            conn.Open();
            MySqlCommand cmd = conn.CreateCommand();
            MySqlDataReader reader = null;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT * FROM `user` Where UserName '" + User.Text + "' and Full_Name = '" + Fname.Text + "' and Password = '" + Pass.Text + "'";
            reader = cmd.ExecuteReader();
            MessageBox.Show("Please Try Again:");
            if (reader.Read())
            {
                DashBoard Db = new DashBoard();
                Db.Show();
                this.Close();
                MessageBox.Show("Login success:");
            }

            conn.Close();
        }
        catch
        {
            MessageBox.Show("Connection failed:");
        }
    }
}

标签: c#mysql

解决方案


我认为是语法错误,只需更改"SELECT * FROM user Where UserName '" + User.Text + ""SELECT * FROM user Where UserName = '" + User.Text + ". 可能您错过了 (=),因此它会引发 Sql 语法异常并导致连接失败。


推荐阅读