How does one export a Room table to a CSV format?

前端 未结 3 1034
广开言路
广开言路 2021-02-04 22:29

I have an app right now that stores data in a Room database using several entities. What I need is to take the contents of a table, convert the data into a CSV format, and then

3条回答
  •  鱼传尺愫
    2021-02-04 23:14

    I understand that I can get the path to the actual database and manipulate that file. However, Google has gone to such lengths to obscure the SQLite details that this seems like a bad idea.

    Google offers getOpenHelper() on your RoomDatabase, if you have a reason to want to work with the database more directly (e.g., execute arbitrary SQL that is not in your DAO).

    I know that I can also write a query method in one of the DAOs that returns a string in CSV format that can then be turned into a File object

    IMHO, creating a CSV file is not the responsibility of a DAO, any more than populating widgets is the responsibility of a DAO.

    How do I export a Room database table into a CSV formatted string?

    Create some sort of Report class that can query the DAO, generate the CSV, and write it to your desired location.

    Or, find some existing code that can take a Cursor and generate a CSV from it. Use getOpenHelper() to get a SupportSQLiteDatabase, on which you can query() with your desired SQL to generate the Cursor.

    Is there any preferred way to back up the entire database?

    IMHO, close() the RoomDatabase, then copy the files (using getDatabasePath() and Java file I/O).

提交回复
热议问题