如何使用SQLiteStatement将空值插入Sqlite

Mar*_*och 3 android sql-insert android-sqlite

我试着保存到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();
    }
//...
}
Run Code Online (Sandbox Code Playgroud)

一切工作确定,当两者getmWho()getmWhat()返回非null数值.但是当我尝试保存具有Who字段为空的事件(并因此getmWho()返回null)时,我收到错误

java.lang.IllegalArgumentException: the bind value at index 1 is null
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?

laa*_*lto 6

使用bindNull()而不是bindString()绑定null的值.

或者,由于您在绑定新值之前清除所有绑定,因此不要绑定任何空字符串.如果未将任何值绑定到某个位置,则会假定使用默认值null.