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

时间:2014-11-18 20:32:17

标签: java android sqlite

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

3 个答案:

答案 0 :(得分: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;
    }

}

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

答案 1 :(得分:2)

我稍微改了一下:将Cursor分隔为String(可以单独使用),设计为Table print。

public String tableToString(SQLiteDatabase db, String tableName) {
    Log.d("","tableToString called");
    String tableString = String.format("Table %s:\n", tableName);
    Cursor allRows  = db.rawQuery("SELECT * FROM " + tableName, null);
    tableString += cursorToString(allRows);
    return tableString;
}

public String cursorToString(Cursor cursor){
    String cursorString = "";
    if (cursor.moveToFirst() ){
        String[] columnNames = cursor.getColumnNames();
        for (String name: columnNames) 
            cursorString += String.format("%s ][ ", name);
        cursorString += "\n";
        do {
            for (String name: columnNames) {
                cursorString += String.format("%s ][ ",
                        cursor.getString(cursor.getColumnIndex(name)));
            }
            cursorString += "\n";
        } while (cursor.moveToNext());
    }
    return cursorString;
}

答案 2 :(得分:1)

另一个更快的选择是使用root设备,然后将app数据库导出到您的开发机器,以便使用能够读取sqlite dbs的桌面应用程序打开。 Google Play上还有一个名为sqlite debugger的应用程序,您可以使用它来查看应用程序数据库,但这又需要root。