![](/img/trans.png)
[英]InvalidOperationException: Invalid attempt to read when no data is present. (SQL)
[英]InvalidOperationException when i try to retrieve a password from database, “Invalid attempt to read when no data is present.”
这是我的代码,我需要从数据库中检索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();
}
}
}
执行时出现此错误:
System.Data.dll中发生了类型为'System.InvalidOperationException'的未处理异常
附加信息:当没有数据时,读取尝试无效。
reader.Read()
方法返回一个布尔值,以指示是否实际上已读取任何内容-您根本不需要检查...。
将您的代码更改为:
if(reader.Read())
{
Pass = reader["Login_Password"].ToString();
if (tbOldPassword.Text == Pass)
MessageBox.Show("Password matches");
else
MessageBox.Show("Password wrong");
}
如果什么也没读,我想您的用户不存在-我不确定在这种情况下您想做什么......由您决定
但是请告诉我您不是在数据库中以明文形式存储密码!
似乎数据库中没有要检查的用户名的条目。 请检查阅读器是否返回结果:
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();
while(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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.