Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging SQL queries in android

I am using the query functions in order to build the SQL queries for my tables. Is there a way to see the actual query that is run? For instance log it somewhere?

So far the best I could do was to have a look at the cursor's member mQuery using a breakpoint. I'd love to output the queries automatically though. This member is of course not public and does not have a getter.


Just for the record, here is an implementation of the accepted answer.

/**  * Implement the cursor factory in order to log the queries before returning   * the cursor  *   * @author Vincent @ MarvinLabs  */ public class SQLiteCursorFactory implements CursorFactory {      private boolean debugQueries = false;      public SQLiteCursorFactory() {         this.debugQueries = false;     }      public SQLiteCursorFactory(boolean debugQueries) {         this.debugQueries = debugQueries;     }      @Override     public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery,                              String editTable, SQLiteQuery query) {         if (debugQueries) {             Log.d("SQL", query.toString());         }         return new SQLiteCursor(db, masterQuery, editTable, query);     } } 
like image 275
Vincent Mimoun-Prat Avatar asked May 11 '11 15:05

Vincent Mimoun-Prat


2 Answers

adb shell setprop log.tag.SQLiteStatements VERBOSE 

Don't forget to restart your app after setting this property.

It is also possible to enable logging of execution time. More details are availabe here: http://androidxref.com/4.2.2_r1/xref/frameworks/base/core/java/android/database/sqlite/SQLiteDebug.java

like image 89
Tema Avatar answered Sep 21 '22 13:09

Tema


You can apply your own SQLiteDatabase.CursorFactory to the database. (See the openDatabase parameters.) This will allow you to create your own subclass of Cursor, which keeps the query in an easily accessible field.

edit: In fact, you may not even have to subclass Cursor. Just have your factory's newCursor() method return a standard SQLiteCursor, but log the query before doing so.

like image 45
Graham Borland Avatar answered Sep 21 '22 13:09

Graham Borland