在android中记录SQL查询 [英] Logging SQL queries in android

查看:24
本文介绍了在android中记录SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 query 函数来为我的表构建 SQL 查询.有没有办法查看运行的实际查询?例如将它记录在某个地方?

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?

到目前为止,我能做的最好的事情就是使用断点查看游标的成员 mQuery.我很想自动输出查询.这个成员当然不是公开的,也没有 getter.

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

推荐答案

您可以将自己的 SQLiteDatabase.CursorFactory 应用到数据库中.(参见 openDatabase 参数.)这将允许您创建自己的 Cursor 子类,从而使查询保持在易于访问的字段中.

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:实际上,您甚至可能不必对Cursor 进行子类化.只需让您工厂的 newCursor() 方法返回标准的 SQLiteCursor,但在此之前记录查询.

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.

这篇关于在android中记录SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆