在Sqlite表中插入null

40

我正在尝试在Android中向SQLite表中插入空值。

以下是这个表:

"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对象中跳过它,它会自动将一个空值放入该列吗?

4个回答

80

35

是的,您可以在ContentValues中跳过字段,db.insert将其设置为NULL。 另外,您也可以使用其他方法:

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

这直接将 "column1" 设置为NULL。同时你也可以在更新语句中使用这种方式。


61
不能向put方法发送null值,必须使用putNull方法。 - mSafdel
13
实际上,答案并没有错误。当您检查位于android.content包中的ContentValues.java源代码时,可以看到该方法只是使用提供的空参数调用了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 - Aksel Fatih
6
公共的 void putNull(String key) { mValues.put(key, null); } ... 我想putNull的实现可能会改变,所以最好使用它而不是直接put。尽管如此,这仍然是一个正确的答案。 - samus
1
@Samus Arin,我认为*putNull(String key)*是一个方便的方法,用于将列值设置为null,它的实现不应该改变。 - vovahost
对我来说,当我尝试跳过一个日期字段时,即使该字段不需要为“NOT NULL”,我在使用C#向SQLite插入数据时遇到了问题,出现错误提示“String was not recognized as a valid DateTime”。也许Android代码是不同的。但是我不得不在我的INSERT命令字符串中插入null - vapcguy

1

我认为你可以跳过它,但也可以将其设置为null,只要在首次创建数据库时不将该列声明为“NOT NULL”即可。


对我来说,当我尝试跳过一个日期字段时,即使该字段不需要为“NOT NULL”,我在使用C#向SQLite插入数据时遇到了问题,出现错误提示“String was not recognized as a valid DateTime”。也许Android代码是不同的。但是我不得不在我的INSERT命令字符串中插入null - vapcguy

0
在您的插入查询字符串命令中,您可以插入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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接