Android的SDK提供了一些方便的方法与SQLite的操作数据。然而无论是insert和replace方法使用一些 nullColumnHack
参数,它的用法,我不明白。
该文档解释了它与以下,但如果一个表有多个列,使 NULL
?我真的不明白这一点:/
SQL不允许插入一个完全空行,所以如果initialValues是空的,这个专栏[ /行替换的]将被明确地分配 NULL
值。
让我们假设你有一个名为富
表中所有列要么允许 NULL
值或具有缺省值。
在一些SQL实现,这将是有效的SQL:
INSERT INTO foo的;
这不是SQLite中有效。你必须至少有一列指定的:
INSERT INTO FOO(somecol)VALUES(NULL);
因此,在你传递一个空的 ContentValues
到插入()
,Android和SQLite的需要一些的情况下列,它是安全的分配 NULL
来。如果你有几个这样的列可供选择,通过您所选择的选择机制选择一个:骰子滚动,魔术8球(TM),投硬币,同寝室的室友翻转等
就个人而言,I'd've仅仅是非法的传递一个空 ContentValues
到插入()
,但他们没有问我...: - )
The Android SDK has some convenience methods for manipulating data with SQLite. However both the insert and replace methods use some nullColumnHack
parameter which usage I don't understand.
The documentation explains it with the following, but what if a table has multiple columns that allow NULL
? I really don't get it :/
SQL doesn't allow inserting a completely empty row, so if initialValues is empty, this column [/row for replace] will explicitly be assigned a NULL
value.
解决方案
Let's suppose you have a table named foo
where all columns either allow NULL
values or have defaults.
In some SQL implementations, this would be valid SQL:
INSERT INTO foo;
That's not valid in SQLite. You have to have at least one column specified:
INSERT INTO foo (somecol) VALUES (NULL);
Hence, in the case where you pass an empty ContentValues
to insert()
, Android and SQLite need some column that is safe to assign NULL
to. If you have several such columns to choose from, pick one via the selection mechanism of your choice: roll of the dice, Magic 8-Ball(TM), coin flip, cubicle mate flip, etc.
Personally, I'd've just made it illegal to pass an empty ContentValues
to insert()
, but they didn't ask me... :-)