如何给出正确的错误信息
本文关键字:错误 信息 | 更新日期: 2023-09-27 18:17:38
根据我的代码"您的密码已被成功更改!,祝贺你!"消息弹出,即使更新没有工作。如果更新没有发生,我怎么能给出错误信息(似乎我的更新语句中也有错误……)。实际上,我无法想象如何在这里使用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>");
}
}
cmd1.ExecuteNonQuery()
返回受影响的行数。因此,如果你的查询更新了任何记录,那么它将返回超过0行(在本例中为该用户的1行)所以试试这个
if(cmd1.ExecuteNonQuery()>0)
{
// successfull
}
else
{
// failure
}
和请不要在您的查询中传递这样的值。尝试使用SqlParameter在查询中传递参数,以避免Sql Injection。
Sachin's Answer为您的消息框弹出问题提供解决方案。
但是为什么要实现自己的认证机制?有什么理由不使用asp.net成员提供程序吗?
假设你有很好的理由这样做。但是,如果您正在实现自定义身份验证,请检查此示例成员资格提供程序实现
例如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;
}