SQL 问题 - 不读取 NULL 值

SQL Issue - Does not read NULL value

我在尝试 运行 代码时遇到问题,当我将 PASSWORD= '' 设置为下面的代码时,一切 运行 都很好。

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;
}   

但是当我将我函数中的 PASSWORD=NULL 更改为 sql 时,它显示错误 "Reset Password Failed"。它只读取空字符串而不是 NULL 值。为什么会这样?

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);
    }
}

将您的 SQL str 更改为:

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

你最后的 SQL 是错误的,没有 space 到位。

问题是您需要在 PASSWORD=NULLWHERE 之后添加一个 space(您可能已经在 catch 中为此写了一个日志,说明 invalid syntax near ' 或类似的):

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

But - 避免使用字符串连接一起创建 sql 查询。它容易受到 SQL 注射。而是使用 Parameterized Queries