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?

+3


source to share


2 answers


Use bindNull()

instead bindString()

to bind values ​​that are null.



Or, since you are clearing all bindings before binding new values, just don't bind null strings. If you don't bind any value to a position, the default is null.

+5


source


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.

0


source







All Articles