2011-10-29 26 views
3

我有問題插入布爾值到數據庫。 我有簡單的結構:c#在數據庫中插入布爾值

struct 
{ 
    string name; 
    bool isStudent; 
} 

,我想將其插入到這樣的數據的基礎上:

dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', " + people1.isStudent + ")"; 
dbCommand.ExecuteNonQuery(); 

但我拋出異常:

SQLite的錯誤沒有這樣的列:真

+0

它告訴你,你的領域沒有按在你的數據庫中不存在。你的數據庫結構是什麼? '描述database_table' – Luke

+0

插入'@ string','@string ='標準的SQL注入警告。'' – Hogan

+0

布爾值被存儲爲位'1'或'0'你需要'''':'for這,應該解決你的問題。 – Bastardo

回答

3

嘗試使用:

dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', '" + people1.isStudent + "')"; 

請注意,'true''false'將被引用這種方式。

或者:

int val = isStudent ? 1 : 0; 
dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', " + val + ")"; 

1將用於真正的價值和0虛假值。

1

SQLite沒有bool列類型,而您正在自己構造SQL語句。如果你想這樣做,然後來回轉換1和0。

我也會認爲.net包裝會做到這一點4你。但是你將不得不使用SQL參數,而不是自己構建字符串,甚至給它一個機會來做到這一點。

構建參數化查詢(?)也讓我們的SQL Lite緩存已編譯的語句。

4

使用參數,你會不會擔心值(此外,這是一個很好的做法,避免SQL注入)的報價或格式:

dbCommand.CommandText = "INSERT INTO People (name, isStudent) 
         VALUES (@name, @isStudent)"; 
dbCommand.Parameters.AddWithValue("@name", people1.name); 
dbCommand.Parameters.AddWithValue("@isStudent", people1.isStudent); 
dbCommand.ExecuteNonQuery();