我已经设置了一个简单的主题信息表,其中包含3列:id(自动递增),主题和级别。级别范围介于1和3之间。如果在某个活动中我想在单独的textView中显示级别2的所有主题,我将如何实现此目标?
以下是我的数据库活动代码:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "NCEA_app";
private static final int DATABASE_VERSION = 1;
//table
public static final String TABLE_NAME = "subject_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "SUBJECT";
public static final String COL_3 = "LEVEL";
public static final String CREATE_TABLE = "create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,SUBJECT TEXT,LEVEL INTEGER)";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertSubject(String subject,String level) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,subject);
contentValues.put(COL_3,level);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
}
我认为我需要遍历整个数据库并找到具有正确级别的每个主题,但我是SQL的新手并且不知道如何完成。
答案 0 :(得分:1)
只有使用以下内容才能获得关卡的结果:
public Cursor getLevel2Data(int level) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME + " where " + COL_3 + "="+level,null);
return res;
}
答案 1 :(得分:1)
您可以创建一个这样的方法,以便从您的DatabaseHelper类
中的数据库中获取主题数据public Cursor getSubjectDataForParticularLevel(int level){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT SUBJECT"+TABLE_NAME+" WHERE COL_3 = "+level, null);
return cursor;
}
您可以在此活动中获取您的数据
DatabaseHelper mDatabaseHelper = DatabaseHelper(this);
ArrayList<String> subjectList = new ArrayList<String>();
Cursor cursor = mDatabaseHelper.getSubjectDataForParticularLevel(2);
if (cursor.moveToFirst()) {
do{
//your Subject list
subjectList.add(cursor.getString(cursor.getColumnIndex("SUBJECT")));
} while (cursor.moveToNext());
}
答案 2 :(得分:0)
在Database类中编写一个单独的函数,仅用于查询Level 2条目。 SQL
查询应该像
Select * From Table_name WHERE LEVEL = 2;