gpt4 book ai didi

c# - InvalidOperationException 当我尝试从数据库中检索密码时, "Invalid attempt to read when no data is present."

转载 作者:太空宇宙 更新时间:2023-11-03 20:03:39 24 4
gpt4 key购买 nike

这是我的代码,我需要从数据库中检索LoginPassword

public partial class frmPassword : Form
{
SqlConnection connection = new SqlConnection(@"Data Source=WORKSTATION\SQLEXPRESS;Initial Catalog=TPSystem;Integrated Security=True");

public frmPassword()
{
InitializeComponent();
}

private void btnUpdatePassword_Click(object sender, EventArgs e)
{
frmLogin login = new frmLogin();
string UserN = login.UName;
string Pass;
SqlCommand cmd = new SqlCommand("SELECT Login_Password FROM AdminLogin WHERE Login_Username = '"+UserN+"'", connection);

try
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();

Pass = reader["Login_Password"].ToString();

if (tbOldPassword.Text == Pass)
MessageBox.Show("Password matches");
else
MessageBox.Show("Password wrong");
reader.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "Report", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
finally
{
connection.Close();
}
}
}

我在执行时遇到了这个错误:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll

Additional information: Invalid attempt to read when no data is present.

最佳答案

reader.Read() 方法返回一个 bool 值以指示是否确实读取了任何内容——您根本没有检查它....

将您的代码更改为:

if(reader.Read())
{
Pass = reader["Login_Password"].ToString();

if (tbOldPassword.Text == Pass)
MessageBox.Show("Password matches");
else
MessageBox.Show("Password wrong");
}

如果没有任何内容被读取,我猜你的用户不存在 - 我不确定你想在那种情况下做什么......由你决定

但是告诉我您不是明文存储密码> 在你的数据库中!!!!

关于c# - InvalidOperationException 当我尝试从数据库中检索密码时, "Invalid attempt to read when no data is present.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25486914/

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