这是我教授构建SQLite数据库的方式,但我觉得应该有更简单的方法。我的大多数列总是以相同的默认值开头,所以有一种方法可以在我创建表时设置默认值。
public class SQLiteTable {
public static final String KEY_ROWID = "_id";
public static final String KEY_LEVEL = "level";
public static final String KEY_HEALTH = "health";
public static final String KEY_NAME = "name";
public static final String KEY_CRIT = "crit";
public static final String KEY_CRIT_RANGE = "crit_range";
public static final String KEY_CRIT_INC = "crit_increment";
public static final String KEY_HIT_RANGE = "hit_range";
public static final String KEY_HIT_INC = "hit_increment";
public static final String KEY_CHAR_IMG = "character_image";
public static final String KEY_TOTAL_XP = "total_xp";
public static final String KEY_XP = "xp";
public static final String KEY_XP_NEEDED = "xp_needed";
public static final String KEY_COINS = "coins";
public static final String KEY_SMALL_POTS = "small_pots";
public static final String KEY_LARGE_POTS = "large_pots";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static final String DATABASE_NAME = "Battle For Christams";
private static final String DATABASE_TABLE = "Application Variables";
private static final int DATABASE_VERSION = 1;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_LEVEL + " TEXT NOT NULL, " +
KEY_HEALTH + " TEXT NOT NULL, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_CRIT + " TEXT NOT NULL, " +
KEY_CRIT_RANGE + " TEXT NOT NULL, " +
KEY_CRIT_INC + " TEXT NOT NULL, " +
KEY_HIT_RANGE + " TEXT NOT NULL, " +
KEY_HIT_INC + " TEXT NOT NULL, " +
KEY_CHAR_IMG + " TEXT NOT NULL, " +
KEY_TOTAL_XP + " TEXT NOT NULL, " +
KEY_XP + " TEXT NOT NULL, " +
KEY_XP_NEEDED + " TEXT NOT NULL, " +
KEY_COINS + " TEXT NOT NULL, " +
KEY_SMALL_POTS + " TEXT NOT NULL, " +
KEY_LARGE_POTS + " TEXT NOT NULL)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE);
onCreate(db);
}
}