@Override public ArrayList<Relation> queryRelation( Class class1, Class class2, List<String> key1List, List<String> key2List) { acquireReference(); try { SQLStatement stmt = SQLBuilder.buildQueryRelationSql(class1, class2, key1List, key2List); final EntityTable table1 = TableManager.getTable(class1); final EntityTable table2 = TableManager.getTable(class2); final ArrayList<Relation> list = new ArrayList<Relation>(); Querier.doQuery( mHelper.getReadableDatabase(), stmt, new Querier.CursorParser() { @Override public void parseEachCursor(SQLiteDatabase db, Cursor c) throws Exception { Relation relation = new Relation(); relation.key1 = c.getString(c.getColumnIndex(table1.name)); relation.key2 = c.getString(c.getColumnIndex(table2.name)); list.add(relation); } }); return list; } finally { releaseReference(); } }
/** * 数据库分析 通过读数据库得到一张表的全部列名 * * @param db * @param tableName * @return */ public ArrayList<String> getAllColumnsFromSQLite(SQLiteDatabase db, final String tableName) { final EntityTable table = getTable(SQLiteColumn.class, false); final ArrayList<String> list = new ArrayList<String>(); SQLStatement st = SQLBuilder.buildColumnsObtainAll(tableName); Querier.doQuery( db, st, new Querier.CursorParser() { @Override public void parseEachCursor(SQLiteDatabase db, Cursor c) throws Exception { SQLiteColumn col = new SQLiteColumn(); DataUtil.injectDataToObject(c, col, table); list.add(col.name); } }); return list; }
/** * 初始化全部表及其列名,初始化失败,则无法进行下去。 * * @param db */ private void initAllTablesFromSQLite(SQLiteDatabase db) { synchronized (mSqlTableMap) { if (Checker.isEmpty(mSqlTableMap)) { if (Log.isPrint) { Log.i(TAG, "Initialize SQL table start--------------------->"); } SQLStatement st = SQLBuilder.buildTableObtainAll(); final EntityTable table = getTable(SQLiteTable.class, false); Querier.doQuery( db, st, new Querier.CursorParser() { @Override public void parseEachCursor(SQLiteDatabase db, Cursor c) throws Exception { SQLiteTable sqlTable = new SQLiteTable(); DataUtil.injectDataToObject(c, sqlTable, table); ArrayList<String> colS = getAllColumnsFromSQLite(db, sqlTable.name); if (Checker.isEmpty(colS)) { // 如果读数据库失败了,那么解析建表语句 Log.e(TAG, "读数据库失败了,开始解析建表语句"); colS = transformSqlToColumns(sqlTable.sql); } sqlTable.columns = new HashMap<String, Integer>(); for (String col : colS) { sqlTable.columns.put(col, 1); } if (Log.isPrint) { Log.d(TAG, "Find One SQL Table: " + sqlTable); } mSqlTableMap.put(sqlTable.name, sqlTable); } }); if (Log.isPrint) { Log.i(TAG, "Initialize SQL table end ---------------------> " + mSqlTableMap.size()); } } } }