在Android中打印SQLite数据库的所有行

A.W*_*Wan 6 java sqlite android

出于调试/检查点的目的,我想在Android中打印出SQLite数据库的所有行.我没有找到任何回答这个问题的答案:如何以人类可读的格式轻松打印出SQLite数据库的所有行?

A.W*_*Wan 15

我想出的解决方案如下:

public class DbHelper extends SQLiteOpenHelper {
    String TAG = "DbHelper";
    ... // functions omitted


    /**
     * Helper function that parses a given table into a string
     * and returns it for easy printing. The string consists of 
     * the table name and then each row is iterated through with
     * column_name: value pairs printed out.
     *
     * @param db the database to get the table from
     * @param tableName the the name of the table to parse
     * @return the table tableName as a string
     */
    public String getTableAsString(SQLiteDatabase db, String tableName) {
        Log.d(TAG, "getTableAsString called");
        String tableString = String.format("Table %s:\n", tableName);
        Cursor allRows  = db.rawQuery("SELECT * FROM " + tableName, null);
        if (allRows.moveToFirst() ){
            String[] columnNames = allRows.getColumnNames();
            do {
                for (String name: columnNames) {
                    tableString += String.format("%s: %s\n", name,
                            allRows.getString(allRows.getColumnIndex(name)));
                }
                tableString += "\n";

            } while (allRows.moveToNext());
        }

        return tableString;
    }

}
Run Code Online (Sandbox Code Playgroud)

希望这有助于你们中的一些人.