【问题标题】:C# - Cannot get value from databaseC# - 无法从数据库中获取值
【发布时间】:2017-10-06 18:52:48
【问题描述】:

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

 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.");
     }            
 }

【问题讨论】:

  • mConn 变量是否在任何地方初始化?
  • 您是否尝试过使用调试器单步执行您的代码?我很确定它做了某事,但显然不是你期望它做的。
  • 您的代码易受 SQL 注入攻击,通常不安全。密码不应以纯文本形式存储在数据库中。
  • 我正确使用了 mConn,它在代码的其他部分也能正常工作。
  • 我的密码只是一个4位数字,几乎没有任何安全性。

标签: c# mysql database select login


【解决方案1】:

我想提出一些在 cmets 中提到的修复以及一些一般性的改进。有关解决的问题,请参阅代码中的我的 cmets:

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.");
            }
        }
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 2017-09-21
  • 2018-11-30
  • 2021-02-17
相关资源
最近更新 更多