Insert语句不会插入Null值

时间:2011-11-07 02:07:25

标签: c# asp.net sql

我正在尝试从C#向我的数据库插入一个空值,如下所示:

SqlCommand command = new SqlCommand("INSERT INTO Employee
VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text
        + "','" + phone.Text + "','" + DBNull.Value + "')", connection);

DBNull.Value是一个日期可以但我希望它等于null但它似乎放入一个默认日期,1900年......

6 个答案:

答案 0 :(得分:10)

使用参数。

SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES 
            (@employeeID,@name,@age,@phone,@bdate)",connection);
....
command.Parameters.AddWithValue("@bdate",DBNull.Value);
//or
command.Parameters.Add("@bdate",System.Data.SqlDbType.DateTime).Value=DBNull.Value;

或试试这个,

 SqlCommand command = new SqlCommand("INSERT INTO Employee 
         (employeeID,name,age,phone) VALUES 
                (@employeeID,@name,@age,@phone)",connection);

答案 1 :(得分:8)

更改为:

SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text + "','" + phone.Text + "',null)", connection);

DBNull.Value.ToString()返回空字符串,但你想要null。

但是,这种构建查询的方式可能会导致问题。例如,如果您的某个字符串包含引号,则生成的查询将引发错误。更好的方法是使用参数并在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));

答案 2 :(得分:1)

将DBNull.Value更改为动态SQL的文字null:

SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text + "','" + phone.Text + "',null)", connection);

答案 3 :(得分:1)

试试这个:

SqlCommand command = new SqlCommand();
command.ComandText = "insert into employee values(@employeeId, @name, @age, @phone, @someNullVal)";
command.Parameters.AddWithValue("@employeedId", employeedID.Text);
// all your other parameters
command.Parameters.AddWithValue("@someNullVal", DBNull.Value);

这解决了两个问题。你明确的问题(在表中插入一个NULL值)和SQL Injection潜在的。

答案 4 :(得分:1)

如果输出"'" + DBNull.Value + "'",你会发现它是'',这意味着你在数据库中插入一个空字符串而不是null。所以,你只需写入null:

SqlCommand command = new SqlCommand("INSERT INTO Employee
VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text
        + "','" + phone.Text + "', null)", connection);

答案 5 :(得分:0)

尝试这样。

SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text + 
         "','" + name.Text + "','" + age.Text + "','" + phone.Text + "','Null')", connection);