sql server连接到db

时间:2012-12-26 19:26:16

标签: c# sql-server

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

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();

1 个答案:

答案 0 :(得分: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;
    }
}