定义schema:

 1 public final class FeedReaderContract {
 2     // To prevent someone from accidentally instantiating the contract class,
 3     // give it an empty constructor.
 4     public FeedReaderContract() {}
 5 
 6     /* Inner class that defines the table contents */
 7     public static abstract class FeedEntry implements BaseColumns {
 8         public static final String TABLE_NAME = "entry";
 9         public static final String COLUMN_NAME_ENTRY_ID = "entryid";
10         public static final String COLUMN_NAME_TITLE = "title";
11         public static final String COLUMN_NAME_SUBTITLE = "subtitle";
12         ...
13     }
14 }

自定义SQL Helper:

 1 public class FeedReaderDbHelper extends SQLiteOpenHelper {
 2     // If you change the database schema, you must increment the database version.
 3     public static final int DATABASE_VERSION = 1;
 4     public static final String DATABASE_NAME = "FeedReader.db";
 5 
 6    private static final String TEXT_TYPE = " TEXT";
 7    private static final String COMMA_SEP = ",";
 8    private static final String SQL_CREATE_ENTRIES =
 9     "CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
10     FeedEntry._ID + " INTEGER PRIMARY KEY," +
11     FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
12     FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
13     ... // Any other options for the CREATE command
14     " )";
15 
16 private static final String SQL_DELETE_ENTRIES =
17     "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;
18 
19 
20     public FeedReaderDbHelper(Context context) {
21         super(context, DATABASE_NAME, null, DATABASE_VERSION);
22     }
23     public void onCreate(SQLiteDatabase db) {
24         db.execSQL(SQL_CREATE_ENTRIES);
25     }
26     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
27         // This database is only a cache for online data, so its upgrade policy is
28         // to simply to discard the data and start over
29         db.execSQL(SQL_DELETE_ENTRIES);
30         onCreate(db);
31     }
32     public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
33         onUpgrade(db, oldVersion, newVersion);
34     }
35 }
View Code

相关文章: