我有Employee类,具有以下属性
class Employee{
public int? EmployeeId {get; set;}
public string Name{get; set;}
public decimal? Salary{get; set;}
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个对象
Employee emp = new Employee(){EmployeeId = 10, Name = "Peter", Salary = 1000.0}
Run Code Online (Sandbox Code Playgroud)
我在下面写了在LoadEmployee()方法中插入查询以将Employee对象数据插入Employee表
public static void LoadEmployee(Employee obj){
string sqlString = @"Insert into dbo.Employee (EmpId, Name, Salary values ('"+ obj.EmployeeId + "','"+ obj.Name + "','"+obj.Salary"')";
SqlCommand queryCommand = new SqlCommand(sqlString, this.sdwDBConnection);
queryCommand.Executereader();
}
Run Code Online (Sandbox Code Playgroud)
当我们为EmpId,Name或Salary提供非空值时,代码工作正常.挑战是Name或Employee Id或Salary可以为null.我可以使用以下语句为Salary分配null值.
emp.Salary = null;
emp.Name = null;
Run Code Online (Sandbox Code Playgroud)
插入插入查询后,当我在db中验证时,Name更新为字符串值"null",Salary更新为0.我希望将空值插入Employee表中的Name和Salary字段.
请帮助我在这种情况下如何在数据库中为Name或Salary插入null.
使用参数.您必须明确替换null
为DBNull.Value
:
string sqlString = @"insert into dbo.Employee (EmpId, Name, Salary) values (@empId, @name, @salary)";
SqlCommand command = new SqlCommand(sqlString, this.sdwDBConnection);
command.Parameters.Add("@empId", SqlDbType.Int).Value = obj.EmployeeId;
command.Parameters.Add("@salary", SqlDbType.Decimal).Value = (object)obj.Salary ?? DBNull.Value;
...
command.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)
永远不要连接字符串来创建查询.它使您容易受到SQL注入攻击.
此外,您queryCommand
不是查询,它是一个命令.所以你不应该把它命名为'query',你应该ExecuteNonQuery
用来执行它.