2011-11-07 119 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);