【问题标题】:How to insert null value to Sqlite with SQLiteStatement如何使用 SQLiteStatement 向 Sqlite 插入空值
【发布时间】:2014-12-17 14:07:40
【问题描述】:

我尝试保存到 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();
    }
//...
}

getmWho()getmWhat() 返回非null 值时,一切正常。但是当我尝试保存 Who 字段为空的事件时(因此 getmWho() 返回 null)我收到错误

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

如何解决这个问题?

【问题讨论】:

    标签: android android-sqlite sql-insert


    【解决方案1】:

    使用bindNull() 而不是bindString() 来绑定空值。

    或者,由于您在绑定新值之前清除了所有绑定,所以不要绑定任何空字符串。当您不绑定任何值到某个位置时,默认值为 null。

    【讨论】:

    • 也许我是个挑剔者,但 bindNull() 绑定的是 null 而不是 null 的“值”。你不能使用 insertStatement.bindNull(1, type.getmWho())。
    【解决方案2】:

    在绑定一个可能为空的值之前,只需询问if(value != null)

    如果以前没有任何价值,我不明白为什么人们经常bindNull()。似乎毫无意义。特别是如果您使用clearBindings()

    API reference for clearBindings: 清除所有现有绑定。未设置的绑定被视为 NULL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 2010-09-25
      相关资源
      最近更新 更多