For debugging/checkpointing purposes, I wanted to print out all rows of a SQLite database in Android. I did not find anything that answered this precise question: How can I easily print out all rows of a SQLite database in a human-readable format?
If you are running the sqlite3 command-line access program you can type ". tables" to get a list of all tables. Or you can type ". schema" to see the complete database schema including all tables and indices.
We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. This method return the total number of columns of the table.
The solution I came up with looks like this:
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;
}
}
Hope this helps some of you.
I changed it a bit: separated the Cursor toString (can be used independently), designed as a 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With