Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert null value to Sqlite with SQLiteStatement

I try 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 OK when both getmWho() and getmWhat() return non-null values. But when I try to save Event which has Who field empty (and thus getmWho() returns null) I'm getting error

java.lang.IllegalArgumentException: the bind value at index 1 is null

How to fix this?

like image 645
Marian Paździoch Avatar asked Sep 05 '25 16:09

Marian Paździoch


1 Answers

Use bindNull() instead of bindString() to bind values that are null.

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

like image 189
laalto Avatar answered Sep 07 '25 05:09

laalto