问题
I have an Android SQLite table definition like this:
create table MyTable(..., myDate integer, ...);
Later in my code I query this table to retrieve the value for myDate via a cursor:
long dateInstant = cursor.getLong(cursor.getColumnIndexOrThrow("myDate"));
However, I'm wondering if this is the best approach. If the value is not set (i.e. null on the database) the above method returns 0, which happens to also be a valid value. I need to differentiate valid values from null values. Also, from the javadoc for getLong
:
The result and whether this method throws an exception when the column value is null, the column type is not an integral type, or the integer value is outside the range [Long.MIN_VALUE, Long.MAX_VALUE] is implementation-defined.
which seems to suggest, if I read this correctly, that at some point in the future the SQLite implementation shipped in Android may choose to throw an exception rather than return 0. I'm looking for a consistent solution across Android versions.
In short, how can I robustly handle the retrieval of integer data from a column in a way which allows me to differentiate between valid values and null?
回答1:
You can do
long dateInstant = 0; // some value to represent null
if (!cursor.isNull (colIndex))
dateInstance = cursor.getLong (colIndex);
来源:https://stackoverflow.com/questions/19989592/how-to-handle-nullable-integer-columns-in-sqlite-database