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

前端 未结 3 1033
广开言路
广开言路 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:13

    It's really easy following these steps:

    1. On Android Studio go to View - Tools - Device Files Explorer
    2. Navigate to /data/data/<your.package>/databases/<your_app_name> and export the file.
    3. Download http://sqlitebrowser.org
    4. Open de DB on SQLite Browser, click Browse Data, select the table.
    5. Go to File - Export - Export table(s) as CSV file...

    Source: https://medium.com/@mattyskala/browse-sqlite-database-in-android-studio-4fbba6cca105

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-02-04 23:33

    It's really easy to export Room DB table to CSV file in Kotlin using kotlin-csv library.

    Just get the list of DB table objects:

    @Dao
    interface DirectorDao {
        @get:Query("SELECT * FROM director ORDER BY full_name ASC")
        val allDirectors: LiveData<List<Director>>
    }
    

    Then user CSV writer to write into the file by going through all list items and adding the column values to CSV rows, one by one, like this:

    csvWriter().open(csvFile) {
        // Header
        writeRow(listOf("[id]", "[name]", "[age]"))
    
        directorDao.allDirectors.value.forEachIndexed { index, director ->
            writeRow(listOf(index, director.fullName, director.age))
        }
    }
    

    I explain the whole flow here.

    0 讨论(0)
提交回复
热议问题