更改为:
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text + "','" + phone.Text + "',null)", connection);
DBNull.Value.ToString()
返回空字符串,但您想要空值。
但是,这种构建查询的方式可能会导致问题。例如,如果其中一个字符串包含引号,则结果查询会引发错误。更好的方法是使用参数并在SqlCommand对象上设置:
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES (@empId,@name,@age,@phone,null)", connection);
command.Parameters.Add(new SqlParameter("@empId", employeeId.Text));
command.Parameters.Add(new SqlParameter("@name", name.Text));
command.Parameters.Add(new SqlParameter("@age", age.Text));
command.Parameters.Add(new SqlParameter("@phone", phone.Text));
绝不会生成如此的SQL查询,而是使用命令参数。否则,有人会输入名称为“)的雇员; DELETE * FROM EMPLOYEE; - ” –
这似乎允许[SQLi](http://en.wikipedia.org/wiki/Sql_injection)。你意识到这些影响? –
非常感谢 – Steve