如何在更改之前检查旧密码是否匹配?

时间:2015-01-16 16:48:32

标签: c# sql .net ado.net

我有这段代码:

//Update login query
string sql = "ALTER LOGIN " + login.ToUpper() + " WITH PASSWORD = '" + password + "' OLD_PASSWORD = '" + oldpassword + "'";

//Try connection and execute
using (SqlConnection connection = new SqlConnection(GetConnection()))
{
     connection.Open();

     SqlCommand command = new SqlCommand(sql, connection);
     command.CommandType = System.Data.CommandType.Text;
     var result = command.ExecuteScalar();
     connection.Close();
}

此sql查询更改数据库中登录的密码。请注意,它需要旧密码才能继续。尽管如此,如果我传递了错误的旧密码,那么它会抛出一个SQLException:

  

无法更改登录'SEVA',因为它不存在或您没有权限。

在执行此查询之前,如何检查旧密码是否正确,以便向用户显示错误消息?

1 个答案:

答案 0 :(得分:1)

试试这个。你需要在catch中添加一些东西告诉用户他没有输入正确的密码

        //Update login query
        string sql = "ALTER LOGIN " + login.ToUpper() + " WITH PASSWORD = '" + password + "' OLD_PASSWORD = '" + oldpassword + "'";

        try {
        //Try connection and execute
        using (SqlConnection connection = new SqlConnection(GetConnection()))
        {
             connection.Open();

             SqlCommand command = new SqlCommand(sql, connection);
             command.CommandType = System.Data.CommandType.Text;
             var result = command.ExecuteScalar();
             connection.Close();
        }
    }
    catch(SQLException)
    {
//Do something here to tell the user something went wrong
    }