How to handle nullable integer columns in SQLite database

断了今生、忘了曾经 提交于 2019-12-24 19:29:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!