我正在拼命尝试建立一个包含多个表的数据库,如下所示:
nutrition.db:
Ingredient(ID, name, kcal);
Meal(ID, name, ingredientId1, ingredientId2);
MealInstance(ID, mealId, date, amountOfIngr1, amountOfIngr2) ...
我偶然发现了各种各样的方法 - 例如,通过使用大量的交换机案例或者基于构建整个CRUD接口来扩展类似于记事本教程(扩展 ContentProvider)的Provider类在.execSQL上。然而,对于这样一个简单(和常见的)任务而言,所有这些对我来说似乎都很荒谬,这就是为什么我认为我忽略了一些东西。由于一些奇怪的原因,我检查过的所有教程只使用一个DB和一个表。
我非常感谢教程推荐或一些提示。
答案 0 :(得分:2)
我建议您查看Google的应用 ioshed 。
数据库的源代码:ioshed - database source code
答案 1 :(得分:0)
要创建一个维护多个SQLite表的Android应用,以下是一个示例:
public class MyDatabase {
private static final String DATABASE_NAME = "my_database.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_ONE = "tableOne";
public static final String TABLE_TWO = "tableTwo";
public static final String TABLE_THREE = "tableThree";
public MyDatabase(Context _context)
{
mDbHelper = new MyDbOpenHelper(_context, DATABASE_NAME, null, DATABASE_VERSION);
}
//add code to declare your columns for each table
//add methods for opening/closing database, etc...
private static class MyDbOpenHelper extends SQLiteOpenHelper {
//SETUP THE NORMAL SQLite COMMANDS THAT YOU USE TO CREATE A TABLE
private static final String CREATE_TABLE_ONE = "create table if not exists " + TABLE_ONE...;
private static final String CREATE_TABLE_TWO = "create table if not exists " + TABLE_TWO...;
private static final String CREATE_TABLE_THREE = "create table if not exists " + TABLE_THREE...;
public StatsDbOpenHelper(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase _db)
{
//ALL OF YOUR TABLES ARE CREATED HERE WHEN YOUR DATABASE IS FIRST CREATED
_db.execSQL(CREATE_TABLE_ONE);
_db.execSQL(CREATE_TABLE_TWO);
_db.execSQL(CREATE_TABLE_THREE);
}
}
}