这是我的代码,我需要从数据库中检索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.InvalidOperationException' 发生在System.Data.dll
中其他信息:无效尝试 在没有数据时读取。
答案 0 :(得分:4)
reader.Read()
方法返回一个布尔值来指示实际上是否读过任何内容 - 你根本就没有检查过....
将您的代码更改为:
if(reader.Read())
{
Pass = reader["Login_Password"].ToString();
if (tbOldPassword.Text == Pass)
MessageBox.Show("Password matches");
else
MessageBox.Show("Password wrong");
}
如果没有读到任何内容,我猜你的用户不存在 - 我不确定你在那种情况下想做什么......由你决定
但 请 告诉我你 不 以明文存储密码>在您的数据库中!!!!
答案 1 :(得分:1)
似乎数据库中没有您要检查的用户名的条目。请检查是否有结果返回结果:
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();
}
}
}