How to insert null into Sqlite using SQLiteStatement
I am trying to save to Sqlite Event
public class EventDao{
private SQLiteStatement insertStatement;
private SQLiteDatabase db;
private static final String INSERT =
"insert into " + EventsTable.TABLE_NAME + "(" + EventsColumns.WHO + ", "
+ EventsColumns.WHAT
+ ") values (?, ?)";
public EventDao(SQLiteDatabase db) {
this.db = db;
Log.w(TAG, EventDao.INSERT);
insertStatement = db.compileStatement(EventDao.INSERT);
}
public long save(Event type) {
insertStatement.clearBindings();
insertStatement.bindString(1, type.getmWho());
insertStatement.bindString(2, type.getmWhat());
return insertStatement.executeInsert();
}
//...
}
Everything works fine when values getmWho()
and are getmWhat()
not returned null
. But when I try to save an event that has an Who
empty field (and therefore getmWho()
returns null
), I get the error
java.lang.IllegalArgumentException: the bind value at index 1 is null
How to fix it?
source to share
Just ask if(value != null)
before binding the value, which can be null.
I never understood why people often bindNull()
, if there were no restrictions before. Seems pointless. Especially if you are using clearBindings()
.
API reference for clearBindings: Removes all existing bindings. Undo bindings are treated as NULL.
source to share