-1

I have an issue when I try to run the code, everything runs well when I set my PASSWORD= '' as the code below.

public int ClearEmployeePasswordById(Employee p)
{
    int result = -1;        
    try
    {               
        string sql = "UPDATE EMPLOYEE SET " +
                     "PASSWORD=''" +
                     "WHERE Employee_Id=" + p.EmployeeId;

        Common.logToFile("PosNet.Data.Sybase.cs", "ClearEmployeePasswordById", sql);
        string r = ExecuteNonQuery(sql);

        if (!string.IsNullOrEmpty(r))
            throw new Exception(r);

        result = 1;
        InsertAuditLog();
    }
    catch (Exception ex)
    {
        Common.logErrorToFile("PosNet.Data.Sybase.cs", "ClearEmployeePasswordById", ex.Message);
        //throw ex;
    }
    return result;
}   

But when I change the PASSWORD=NULL at my function with the sql, it shows the error "Reset Password Failed". It just read the empty string but not the NULL value. Why does it happen?

private void btnPasswordReset_Click(object sender, EventArgs e)
{
    try
    {
        string employeeWithoutQuote = lblEmployeeId.Text.Substring(1, 10);
        int employeeId = int.Parse(employeeWithoutQuote);
        Employee employee = MF.BC.DA.GetEmployeeByBarcode(employeeId);
        if (MF.BC.DA.ClearEmployeePasswordById(employee) != 1)
        {
            throw new Exception("Reset Password Failed");
        }
        else
        {
            MessageBox.Show("Reset Password Success");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Muhammad Saifullah
  • 87
  • 1
  • 3
  • 15

2 Answers2

3

The problem is that you need to have a space after the PASSWORD=NULL and the WHERE (you probably have written a log for that in your catch stating invalid syntax near ' or similar):

string sql = "UPDATE EMPLOYEE SET " +
             "PASSWORD = NULL "
             "WHERE Employee_Id=" + p.EmployeeId;

But - Avoid using string concatenation for creating sql queries all together. It is susceptible for SQL Injections. Instead use Parameterized Queries

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
2

Changes your SQL str to this:

string sql = 
    "UPDATE EMPLOYEE SET " +
    "PASSWORD=NULL " + //NOTE: Added a space
    "WHERE Employee_Id=" + p.EmployeeId;

Your final SQL is wrong without the space in place.

webnoob
  • 15,747
  • 13
  • 83
  • 165