【问题标题】:How to update column with ORMLite如何使用 ORMLite 更新列
【发布时间】:2012-09-19 14:53:25
【问题描述】:

我已经为 Android 应用程序创建了一个数据库,并且我正在使用 ORMLite 来查询 SQLLite。

我在类别中添加了一列,我想在该列中插入数据。 我有行,例如

catId=5 catname="food" catType=?

我想在catId的基础上更新catType。如何使用 ORMLite 中的 catId 更新此 catType 列。

我正在使用这种方法:

Dao<Category, Integer> catDao = getHelper().getCategoryDao();
QueryBuilder<Category, Integer> queryBuilder = catDao.queryBuilder();
queryBuilder.where().eq("categoryId", 5);
PreparedQuery<Category> pq = queryBuilder.prepare();
Category category = catDao.queryForFirst(pq);
category.setCategoryType("BarType");
catDao.createOrUpdate(category);

请给我一个更好的解决方案。

【问题讨论】:

  • 这个有什么问题?
  • njzk2,它比较慢,因为它执行 2 个数据库操作而不是 1 个

标签: android sqlite ormlite


【解决方案1】:

我想在catId的基础上更新catType。如何使用 ORMLite 中的 catId 更新此 catType 列。

ORMLite 也支持UpdateBuilder。以下是你可以如何使用它:

UpdateBuilder<Category, Integer> updateBuilder = catDao.updateBuilder();
// set the criteria like you would a QueryBuilder
updateBuilder.where().eq("categoryId", 5);
// update the value of your field(s)
updateBuilder.updateColumnValue("catType" /* column */, "BarType" /* value */);
updateBuilder.update();

有关更多示例,请参阅UpdateBuilder docs

【讨论】:

    【解决方案2】:
    Dao<Category, Integer> catDao = getHelper().getCategoryDao();
    List <Category> categoryList = catDao.queryForAll();
    for (Category c: categoryList ) {
        c.setCategoryType("BarType");
        catDao.update(c);
    }
    

    【讨论】:

    • 对同一实体(但在不同字段上)的并发更新可能会相互覆盖。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多