0

我做了一些更多的研究并想出了别的东西。但是,这次消息框显示密码已更改,但是当我刷新数据库中的页面时,它没有更改。这是代码:

SqlConnection sqlconn = new SqlConnection();

sqlconn.ConnectionString = @" ";          
sqlconn.Open();
string empCode = comboEmpCode.Text;
string oldPwd = txtOldPwd.Text;
string newPwd = txtNewPwd.Text;
string confirmPwd = txtConNewPwd.Text;
string sqlquery = "UPDATE [Employee] SET Pwd=@newpass where EmployeeCode=@empcode";
SqlCommand cmd = new SqlCommand(sqlquery, sqlconn);
cmd.Parameters.AddWithValue("@newpass", txtNewPwd.Text);
cmd.Parameters.AddWithValue("@empcode", comboEmpCode.Text);
cmd.Parameters.AddWithValue("@oldPwd", txtOldPwd.Text);
cmd.Connection = sqlconn;
cmd.ExecuteNonQuery();
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
    if ((txtNewPwd.Text == reader["newPwd"].ToString()) & (txtConNewPwd.Text == (reader["confirmPwd"].ToString()))) { }
}
MessageBox.Show("Password was changed Successfully!", "Password Change", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
4

1 回答 1

2

看一下这个方法,如果更新成功则返回 true,如果更新不成功则返回 false,我添加了消息框以在故障排除期间提供一些清晰性。此外,我将您的 SQLConnection 和 SQLCommand 对象包装在 Using 语句中,当您完成它们时,它们应该可以很好地处理这些对象。

public bool ChangePassword(string empCode, string newPassword, string oldPassword)
{
    string connectionString = "@<Enter your Connection String Here>";

    string sql = "UPDATE [Employee] SET Pwd=@newpass where EmployeeCode=@empcode";

    if (oldPassword != newPassword)
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@newpass", newPassword);
                    cmd.Parameters.AddWithValue("@empcode", empCode);
                    cmd.ExecuteNonQuery();
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(string.Format("{0}-{1}", ex.Message, ex.InnerException));
            return false;
        }
        return true;
    }
    else
    {
        MessageBox.Show(string.Format("Your New password {0}, can not be the same as the old password {1}. Please try again.", newPassword, oldPassword));
        return false;
    }
}
于 2012-12-26T19:49:04.107 回答