我试图在Android应用中实现递归功能;
首先,我尝试了(递归功能)来自' cmd'窗口:
我创建了一个表:
CREATE TABLE tree(
id_tree integer PRIMARY KEY AUTOINCREMENT,
id_boss TEXT,
id_child TEXT,
answ TEXT);
然后插入一些值:
INSERT INTO tree(id_boss,id_child,answ) VALUES('1','2','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('1','3','F');
INSERT INTO tree(id_boss,id_child,answ) VALUES('2','P1','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('2','4','F');
INSERT INTO tree(id_boss,id_child,answ) VALUES('3','P2','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('3','8','F');
然后我运行一个现在可用于sqlite 3.8的递归查询:
WITH RECURSIVE
under_alice(name,level) AS (
VALUES('1','0')
UNION ALL
SELECT tree.id_child, under_alice.level+1
FROM tree, under_alice
WHERE tree.id_boss=under_alice.name
ORDER BY 2 DESC
)
SELECT substr('..........',1,level*3) || name FROM under_alice;
结果运行正常:
1
...2
......4
......P1
...3
......8
......P2
然后我选择id_child,其中id_boss =' 1'并回答=' T'使用此查询;
WITH RECURSIVE
under_alice(name,level) AS (
VALUES('1','0')
UNION ALL
SELECT tree.id_child, under_alice.level+1 FROM tree, under_alice WHERE
tree.id_boss=under_alice.name and answ = 'T' and tree.id_boss='1'
ORDER BY 2 DESC
)
SELECT substr('..........',1,level*3) || name FROM under_alice;
这个结果运行良好:
1
...2
这一切都可以在cmd提示符下运行,但是当我尝试在我的Android应用程序中实现它时,我会遇到一些错误(例如,无法执行):
这是我从Android应用程序执行查询的代码:
try {
SQLiteDatabase db = dbHandler.getWritableDatabase();
String q = "WITH RECURSIVE
under_alice(name,level)
AS ( VALUES('1','0')
UNION ALL
SELECT tree.id_child, under_alice.level+1 FROM tree, under_alice
WHERE tree.id_boss=under_alice.name and answ = 'T' and tree.id_boss='1' ORDER BY 2 DESC)
SELECT max(name) as au FROM under_alice;";
Cursor eq = db.rawQuery(q, null);
eq.moveToFirst();
int au = eq.getColumnIndex("au");
String sau = eq.getString(au);
makeToast(""+sau); // if execute succes, create a toast message
} catch (Exception e) {
// TODO: handle exception
makeToast("failed query"); // if query filed
}
}
如何使这项工作? 我的查询有什么问题吗?