gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:01:22 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于C# - 无法从数据库获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43853247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com