房间数据库:如何将列名检索到字符串列表中? [英] Room database: how to retrieve column names into list of strings?

查看:35
本文介绍了房间数据库:如何将列名检索到字符串列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为addresses"的 Room 表,有 15 列.我检索一行并希望将值放入 List<字符串>,而不是列表<地址 >.这可能吗?

I have a Room table named "addresses" with 15 columns. I retrieve one row and want to get values into List< String >, not List< Addresses >. Is that possible?

@Query("SELECT * FROM addresses WHERE myid= :id")
List<String> getAddressAsList(int id);

此外,是否可以像这样将数据库表列名和值一起检索到映射列表中<"column name","value">?

Moreover, is it possible to retrieve database table column names together with values into list of map <"column name","value"> like this?

@Query("SELECT * FROM addresses WHERE myid= :id")
List<Map<String, String> getAddressAsList(int id);

推荐答案

您可以使用 SupportSQLiteDatabase 但不能使用 Dao.

You can use a SupportSQLiteDatabase but not a Dao.

假设你在一个活动中,

db = yourRoomDatabase.getInstance(this);

  • 即然后你通常会使用类似 yourDao = db.getYourDao(); 的东西,然后myAddressList = dao.getAddressList();
    • i.e. you'd typically then use something like yourDao = db.getYourDao(); and then myAddressList = dao.getAddressList();
    • 然后你可以这样做:-

      SupportSQLiteDatabase sdb = db.getOpenHelper().getWritableDatabase();
      Cursor csr = sdb.query("SELECT * FROM address WHERE myid=?",new String[]{String.value(id)}
      

      然后要获取 Cursor 中的列名列表,您可以使用:-

      Then to get the list of column names in the Cursor you can use:-

          val columnNames = csr.columnNames
      

      要获取列名和值的映射,您可以使用:-

      To get the Map of columnnames and values you could use :-

          val columnsAndValues: MutableMap<String,String> = mutableMapOf()
          while (csr.moveToNext()) {
              for (i: Int in 0..csr.columnCount) {
                  columnsAndValues.put(csr.columnNames.get(i),csr.getString(i))
              }
          }
          csr.close()
      

      这篇关于房间数据库:如何将列名检索到字符串列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆