Search code examples
sqlsqliteandroid-room

How to get SQL statement of table data


I have an SQLite database. I have a table of data. I want to get all the data in the table as a SQL INSERT INTO statement.

For instance, consider we have the following data in the table:

id name
1 Lion
2 Tiger

And, I want the SQL statement of them as follows:

INSERT INTO table_name (id, name)
VALUES (1, "Lion"),
(2, "Tiger");

Is it possible to get like this from the table?


Solution

  • You can build it using StringBuilder:

    val builder = StringBuilder()
    
    builder.append("INSERT INTO ")
       .append(TABLE_NAME)
       .append(" (id, name) VALUES ")
    
    entities.forEach { entity -> 
      builder.append("\n(")
         .append(entity.id)
         .append(", \"")
         .append(entity.name)
         .append("\"),")
    }