根据我的代码“您的密码已成功更改!,恭喜!”即使更新不起作用,也会弹出消息。如果没有进行更新,我该如何给出错误消息(似乎我的更新语句中也存在错误...)。实际上我无法想象如何在这里使用if语句..
protected void Button1_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection("server=localhost; database=e-learningsystem; uid=root; password=123;port=3307;");
connection.Open();
try
{
MySqlCommand cmd1 = new MySqlCommand("UPDATE student Set Password= '" + TextBox3.Text + "' WHERE UserName='" + TextBox1.Text + "' AND Password='"+TextBox2.Text+"'", connection);
cmd1.ExecuteNonQuery();
Response.Write(@"<script language='javascript'>alert('Your Password Has Been Changed successfully!, Congratulations!')</script>");
connection.Close();
}
catch (Exception ex)
{
Response.Write(@"<script language='javascript'>alert(ex.Message)</script>");
}
}
答案 0 :(得分:3)
cmd1.ExecuteNonQuery()
返回受影响的行数。因此,如果您的查询更新任何记录,那么它将返回超过0行(在这种情况下,该特定用户的1行)
所以试试这个
if(cmd1.ExecuteNonQuery()>0)
{
// successfull
}
else
{
// failure
}
并且请不要在查询中传递这样的值。尝试使用 SqlParameter 传递查询中的参数以避免 Sql Injection 。
答案 1 :(得分:0)
Sachin's Answer为您的消息框弹出问题提供解决方案。
但为什么要实现自己的身份验证机制?有没有理由不使用asp.net membership providers?
假设你有充分的理由。但是,如果要实施自定义身份验证,请检查此Sample Membership Provider Implementation
例如ChangePassword方法:
public override bool ChangePassword(string username, string oldPwd, string newPwd)
{
// validate the user first, you are not doing any validation
// logged in user can change any other users password in your approach
if (!ValidateUser(username, oldPwd))
return false;
//new password validation and giving proper message if failed
// skip this code from given link
// use parameterized query as below
OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("UPDATE Users " +
" SET Password = ?, LastPasswordChangedDate = ? " +
" WHERE Username = ? AND ApplicationName = ?", conn);
cmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(newPwd);
cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;
int rowsAffected = 0;
try
{
conn.Open();
// this is how you can check whether row updated or not
rowsAffected = cmd.ExecuteNonQuery();
}
catch (OdbcException e)
{
// you need to have proper error handling as well
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "ChangePassword");
throw new ProviderException(exceptionMessage);
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
if (rowsAffected > 0)
{
return true;
}
return false;
}