2012-03-22 232 views
28

我想知道如何在Android中的SQLite表中插入一個空值。在Sqlite表中插入null

這是表:

"create table my table (_id integer primary key autoincrement, " + 
               "deviceAddress text not null unique, " + 
               "lookUpKey text , " + 
               "deviceName text , " + 
               "contactName text , " + 
               "playerName text , " + 
               "playerPhoto blob " + 
               ");";  

我想通過execSQL使用一個簡單的插入命令,但由於其中一個值是一個blob我不能這樣做(我認爲)。

因此,我使用的是標準的db.Insert命令。 如何使其中一個值爲空?

如果我只是在ContentValues對象中跳過它,它會自動在列中放置一個空值嗎?

回答

16

是的,你可以跳過ContentValues中的字段,db.insert將它設置爲NULL。 你也可以用其他的方式:

ContentValues cv = new ContentValues(); 
cv.putNull("column1"); 
db.insert("table1", null, cv); 

這個directrly組 「列1」 NULL。你也可以在update語句中使用這種方式。

+58

你不能發送null來放置方法,而是你必須使用putNull方法 – mSafdel 2012-12-26 13:28:51

+12

其實答案是沒有錯的。當您檢查位於android.content包中的ContentValues.java的源代碼時,可以看到;該方法只是使用提供的null參數調用put方法。 http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.3_r2.1/android/content/ContentValues.java#ContentValues.putNull%28java.lang.String %29 – Fatih 2013-11-11 14:18:26

+5

** public void putNull(String key){mValues.put(key,null); } ** ...我想putNull的實現可能會改變,所以它可能更好地使用它,而不是直接放置。儘管如此,這仍然是一個正確的答案。 – samosaris 2013-12-19 13:44:40

1

我認爲你可以跳過它,但你也可以把null,只要確保當你第一次創建數據庫時,你不要聲明列爲「NOT NULL」。

+0

對我來說,當我試圖跳過日期字段時,即使該字段不需要爲'NOT NULL',但我嘗試使用C#插入到SQLite時出現問題,提供了一個錯誤,即'字​​符串未被識別爲一個有效的DateTime'。也許Android代碼是不同的。但是我不得不在我的INSERT命令字符串中插入'null'。 – vapcguy 2016-12-08 21:51:43

0

在您的插入查詢字符串命令中,您可以插入null作爲您希望爲null的值。這是C#,因爲我不知道如何爲Android設置數據庫連接,但查詢將是相同的,所以我已將它用於說明目的,我相信您可以將它等同於您自己:

SQLiteConnection conn = new SQLiteConnection(SQLiteConnString()); 
// where SQLiteConnString() is a function that returns this string with the path of the SQLite DB file: 
// String.Format("Data Source={0};Version=3;New=False;Compress=True;", filePath); 

try 
{ 
    using (SQLiteCommand cmd = conn.CreateCommand() 
    { 
     cmd.CommandText = "INSERT INTO MyTable (SomeColumn) VALUES (null)"; 
     cmd.ExecuteNonQuery(); 
    } 
} 
catch (Exception ex) 
{ 
    // do something with ex.ToString() or ex.Message 
}