Web方法不更新SQL服务器上的详细信息

本文关键字:详细信息 服务器 SQL 方法 更新 Web | 更新日期: 2023-09-27 17:51:02

我试图在他们登录后更新学生的详细信息。我希望能够更新他们的密码和电子邮件地址,当他们点击按钮。

[WebMethod]
public bool EditAccount(Student student)
{
    bool UploadSuccess = false;
    cn.Open();
    SqlCommand com = new SqlCommand("UPDATE tblStudent set EmailAddress='" + student.EmailAddress + "', Password='" + student.Password + "'", cn);
    {
        com.Parameters.AddWithValue("@EmailAddress", student.EmailAddress);
        com.Parameters.AddWithValue("@Password", student.Password);
        int i = com.ExecuteNonQuery();
        cn.Close();
        if (i != 0)
        UploadSuccess = true;
        return UploadSuccess;
     }
 }
 protected void btnSave_Click(object sender, EventArgs e)
 {
     Student edit = stu.EditAccount();
     edit.EmailAddress = txtEmail.Text;
     edit.Password = txtPassword2.Text;
     if (stu.EditAccount(edit))
     {
         Response.Write("<script type='"text/javascript'">alert('Successful');</script>");
     }
     else
     {
         Response.Write("<script type='"text/javascript'">alert('Password not matched');</script>");
     }                   
 }

Web方法不更新SQL服务器上的详细信息

你的代码看起来很乱,试着像这样重写它。同时ExecuteNonQuery returns受影响的行数。如果您试图返回的东西尝试使用ExecuteScalarReader

bool UploadSuccess = false;
int i;
cn.Open();
SqlCommand com = new SqlCommand("UPDATE tblStudent set EmailAddress=@EmailAddress, Password=@Password", cn);
{
    com.Parameters.AddWithValue("@EmailAddress", student.EmailAddress);
    com.Parameters.AddWithValue("@Password", student.Password);
    try
    {
        i=com.ExecuteNonQuery();
    }
    catch(Exception e)
    {
        throw e;
    }
    cn.Close();
    if (i != 0)
        UploadSuccess = true;
    return UploadSuccess;
}
[WebMethod]
public bool EditAccount(Student student)
{
    string cmdText = @"UPDATE tblStudent set [EmailAddress]=" + student.EmailAddress +
                      [Password]="+ student.Password +" where [StudentNumber]=" + student.StudentNumber;
    var con = new SqlConnection(constring));
    var SqlCommand com = new SqlCommand{
            CommandType = CommandType.Text,
            CommandText = cmdText ,
            Connection = con 
         };
    try
     { 
        con.Open();
        int i = com.ExecuteNonQuery();
        if (i > 0)
            return true;
      }
      finally
      {
        con.close();
      }
        return false;
}

我建议使用存储过程而不是内联查询,以获得更好的结果。