[学习]SQLite操作(三)

2021-03-03  本文已影响0人  吴敬悦

今天看删除。还是使用第一天创建的表 entry

表目前的状态
我现在有需求,要删除 Python 所在的这条记录:
DELETE FROM entry WHERE subtitle=Python;

android 中可以使用 SQLiteDatabase 为我们提供的 delete 进行删除,在使用之前,先看看 api 的参数说明:

    /**
     * Convenience method for deleting rows in the database.
     *
     * @param table the table to delete from
     * @param whereClause the optional WHERE clause to apply when deleting.
     *            Passing null will delete all rows.
     * @param whereArgs You may include ?s in the where clause, which
     *            will be replaced by the values from whereArgs. The values
     *            will be bound as Strings.
     * @return the number of rows affected if a whereClause is passed in, 0
     *         otherwise. To remove all rows and get a count pass "1" as the
     *         whereClause.
     */
    public int delete(String table, String whereClause, String[] whereArgs) {
        acquireReference();
        try {
            SQLiteStatement statement =  new SQLiteStatement(this, "DELETE FROM " + table +
                    (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
            try {
                return statement.executeUpdateDelete();
            } finally {
                statement.close();
            }
        } finally {
            releaseReference();
        }
    }

返回值是删除的条数。

根据上面的 SQL 语言,我们可以写对应的参数,首先是 table ,填入 entry ;然后是 whereClause 参数:

val whereClause = "${FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE} = ?"

然后就是 whereArgs ,由于这里只有一个问好,所以数组中就一个元素,元素的值就是 Python

val whereArgs = arrayOf("Python")

这样执行上面的函数即可得到删除的条数:

val deletedRows = db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs)

我这里是删除一条,其中 db 我使用的是查询那天拿到的对象:

val db = dbHelper.readableDatabase

我在思考为啥,这个按道理是只能读的,居然也可以用来删除。于是我使用通过下面的方式获取的对象操作了一下,发现也可以:

val db = dbHelper.writableDatabase
上一篇 下一篇

猜你喜欢

热点阅读