Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting null as Integer value into a database

I am trying to store a null value into the database but everytime I load the value I get 0.

I declare the field just like "intVal integer"

This is how I retrieve it:

Integer x;

x = cursor.getInt(cursor.getColumnIndexOrThrow(MyDBAdapter.KEY_X));

Is that reliable? or is it undefined?

So it seems to me one cannot save null as an undefined integervalue

Many thanks

like image 304
user387184 Avatar asked Nov 09 '11 10:11

user387184


People also ask

How do I insert a NULL into an integer?

You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL);

Can integer be NULL in database?

But the short answer is: yes, int columns can have NULL values.

Can you insert a NULL value in SQL?

The SQL INSERT statement can also be used to insert NULL value for a column.

Can integers be NULL in SQL?

An integer column can be null, but '' is an empty string not null. The right syntax for a null integer (or any other sql type) is null .


1 Answers

From the getInt() documentation:

Returns the value of the requested column as an int. 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 [Integer.MIN_VALUE, Integer.MAX_VALUE] is implementation-defined.

So, it's an implementation detail which you shouldn't rely on.

You can still get the effect you want, though: you simply do the null check before you read the value.

int index = cursor.getColumnIndexOrThrow(MyDBAdapter.KEY_X);
Integer x = null;
if (!cursor.isNull(index)
    x = cursor.getInt(index);

// now x is either null or contains a valid value
like image 132
Graham Borland Avatar answered Nov 06 '22 02:11

Graham Borland