2011-11-07 121 views
3

我想从C#中插入一个空值到我的数据库是这样的:Insert语句不会插入Null值

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

DBNull.Value是其中一个日期可以,但我想它想等于空,但它似乎放在一个默认日期,1900东西...

+2

绝不会生成如此的SQL查询,而是使用命令参数。否则,有人会输入名称为“)的雇员; DELETE * FROM EMPLOYEE; - ” –

+0

这似乎允许[SQLi](http://en.wikipedia.org/wiki/Sql_injection)。你意识到这些影响? –

+0

非常感谢 – Steve

回答

7

更改为:

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)); 
+0

非常感谢:) – Steve

1

变化DBNull.Value为动态SQL字面空:

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

尝试这样。

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

看起来好像你在单引号中为空:'Null',我认为这会将字符串“Null”放入字段中。 – akatakritos

+0

我不好,对不起。我会鼓励你在数据库中更改数据类型,将数据存储到varchar中,这样你可以得到空值。 – Givelasdougmore

8

使用参数。

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

+1为好的做法 –

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的潜力。

1

如果你输出"'" + DBNull.Value + "'",你会发现它是'',这意味着你在DB中插入一个空字符串而不是null。因此,您只需写入空值:

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