0

我只在一张表上使用过 SQLite。我现在需要一个包含两个表的数据库。这是我现在的做法:

public class MySQLiteHelper extends SQLiteOpenHelper {

    public static final String TABLE_CAT = "cats";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_CAT = "cat";

    private static final String DATABASE_NAME = "cats.db";
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE = "create table "
            + TABLE_CAT + "( " + COLUMN_ID
            + " integer primary key autoincrement, " + COLUMN_CAT
            + " text not null)";

    public MySQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(MySQLiteHelper.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CAT);
        onCreate(db);
    }

}

除了名为“cats”的表之外,我还想要一个名为“items”的具有相同行的表。对此需要做哪些改变?

注意:此应用仍在测试中,因此我无需担心更新数据库版本。

4

1 回答 1

3

为什么你不能只做两个查询,比如

private static final String DATABASE_CREATE_TABLE_ONE = "create table "
            + TABLE_CAT1 + "( " + COLUMN_ID
            + " integer primary key autoincrement, " + COLUMN_CAT1
            + " text not null)";

private static final String DATABASE_CREATE_TABLE_TWO = "create table "
            + TABLE_CAT2 + "( " + COLUMN_ID
            + " integer primary key autoincrement, " + COLUMN_CAT2
            + " text not null)";

在你的 onCreate 方法中:

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(DATABASE_CREATE_TABLE_ONE );
    db.execSQL(DATABASE_CREATE_TABLE_TWO );
}
于 2013-04-15T18:01:10.503 回答