SQLite数据库的所有行

SQLite数据库的所有行

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

最佳答案

我想出的解决方案如下所示:

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;
    }

}

希望对您有所帮助。

关于java - 在Android中打印SQLite数据库的所有行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27003486/

10-11 17:09