C# - 无法从数据库中获取值

时间:2017-05-08 16:57:31

标签: c# mysql database select login

在我的应用程序中,我有一个登录系统。这是基本的,所以我不需要任何加密。问题是,当我想登录时,我插入凭据(用户名和密码),但它没有做任何事情。我的代码是:

 public void iniciarsessaobutton_Click(object sender, EventArgs e)
 {
     string txtuser = textusername.Text;
     string txtpass = textlogin.Text;      

     MySqlCommand cmd = new MySqlCommand("SELECT password FROM empregados WHERE user='" + txtuser + "';", mConn);
     mConn.Open();           
     MySqlDataReader login = cmd.ExecuteReader();            
     login.Read();            
     string getpass = login["password"].ToString();

     if (getpass == txtpass)
     {                
         mConn.Close();
         MessageBox.Show("Sessão iniciada");
         Admin adm = new Admin();
         this.Hide();
         adm.Show();
     }
     else
     {
         mConn.Close();
         MessageBox.Show("Não foi possivel iniciar sessão. Insira a password corretamente.");
     }            
 }

1 个答案:

答案 0 :(得分:0)

我想提一下评论中提到的一些修正以及一些一般的改进。请参阅我在代码中对所解决问题的评论:

public void iniciarsessaobutton_Click(object sender, EventArgs e)
{
    string txtuser = textusername.Text;
    string txtpass = textlogin.Text;

    // Put your connection into a using() block
    using (MySqlConnection conn = new MySqlConnection(variableWithYourConnectionStringHere))
    {
        // Put your commend into a using() block
        // enclose your column names in backticks to avoid conflict with MySql reserved keywords
        // add a placeholder (@username) for your parameter
        // use LIMIT 1 if you only expect 1 row matching your condition
        using(MySqlCommand cmd = new MySqlCommand("SELECT `password` FROM empregados WHERE `user` = @username LIMIT 1", conn))
        {
            mConn.Open();

            // add a parameter with your TextBox value
            cmd.Parameters.AddWithValue("@username", txtuser);

            // If you only retrieve 1 value, use ExecuteScalar to return only 1 value
            // cast the returned object as string
            string getpass = cmd.ExecuteScalar() as string;

            if (getpass == txtpass)
            {
                MessageBox.Show("Sessão iniciada");
                Admin adm = new Admin();
                this.Hide();
                adm.Show();
            }
            else
            {
                MessageBox.Show("Não foi possivel iniciar sessão. Insira a password corretamente.");
            }
        }
    }
}