示例
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Example.db";
private static final int DATABASE_VERSION = 3;
// 对于所有主键,_id应该用作列名
public static final String COLUMN_ID = "_id";
// 产品表的表和列名的定义
public static final String TABLE_PRODUCTS = "Products";
public static final String COLUMN_NAME = "Name";
public static final String COLUMN_DESCRIPTION = "Description";
public static final String COLUMN_VALUE = "Value";
// 表的定义和Transactions表的列名
public static final String TABLE_TRANSACTIONS = "Transactions";
public static final String COLUMN_PRODUCT_ID = "ProductId";
public static final String COLUMN_AMOUNT = "Amount";
// 创建产品表声明
private static final String CREATE_TABLE_PRODUCT = "创建表 " + TABLE_PRODUCTS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY, " +
COLUMN_DESCRIPTION + " TEXT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_VALUE + " REAL" +
");";
// 创建交易表报表
private static final String CREATE_TABLE_TRANSACTION = "创建表 " + TABLE_TRANSACTIONS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_PRODUCT_ID + " INTEGER," +
COLUMN_AMOUNT + " INTEGER," +
" FOREIGN KEY (" + COLUMN_PRODUCT_ID + ") REFERENCES " + TABLE_PRODUCTS + "(" + COLUMN_ID + ")" +
");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// onCreate应该始终创建您最新的数据库
// 新安装应用程序时调用此方法
db.execSQL(CREATE_TABLE_PRODUCT);
db.execSQL(CREATE_TABLE_TRANSACTION);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// onUpgrade负责在您执行以下操作时升级数据库
//更改架构。对于每个版本,您进行的特定更改
// 该版本中必须使用。
for (int version = oldVersion + 1; version <= newVersion; version++) {
switch (version) {
case 2:
db.execSQL("更改表 " + TABLE_PRODUCTS + " ADD COLUMN " + COLUMN_DESCRIPTION + " TEXT;");
break;
case 3:
db.execSQL(CREATE_TABLE_TRANSACTION);
break;
}
}
}
}