使用Schematic库时如何更新SQLite数据库Schema及升级时创建新表?
I’ve worked with Schematic quite a bit, so let’s break down exactly how to handle adding new tables when upgrading your database version—this should solve the issue you’re facing.
Step 1: Update Your Database Annotation with the New Table and Version
First, you need to increment your database version and add the new table class to the tables array in your @Database annotated class. This tells Schematic about the new table structure.
For example, if your original database looked like this:
@Database(version = 1, tables = {OldTable.class}) public abstract class AppDatabase extends SQLiteOpenHelper { // ... existing code }
Update it to:
@Database(version = 2, tables = {OldTable.class, NewTable.class}) public abstract class AppDatabase extends SQLiteOpenHelper { // ... existing code }
Step 2: Define Your New Table with @Table and @Column Annotations
Create the new table class just like your existing ones, using Schematic’s annotations to define the table name and columns:
@Table(name = "new_table_name") public class NewTable { @Column(name = "_id", type = ColumnType.INTEGER, primaryKey = true, autoIncrement = true) public static final String _ID = "_id"; @Column(name = "column_name", type = ColumnType.TEXT) public static final String COLUMN_NAME = "column_name"; // Add other columns as needed }
Step 3: Handle the Upgrade in onUpgrade
Override the onUpgrade method in your AppDatabase class to create the new table when the version increases. Schematic’s TableUtils class has a handy createTable method that generates the correct SQL from your annotated table class:
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Run migrations based on version differences if (oldVersion < 2) { // Create the new table when upgrading from v1 to v2 TableUtils.createTable(db, NewTable.class); } }
Step 4: Update Your Content Provider (If Needed)
If your new table needs to be accessible via the Content Provider, add its URI to the UriMatcher in your provider class:
public class AppContentProvider extends SchematicProvider { @Override protected List<UriMatcher> getUriMatchers() { return Arrays.asList( UriMatcher.of(OldTable.CONTENT_URI, 1), UriMatcher.of(NewTable.CONTENT_URI, 2) ); } @Override protected Database getDatabase() { return AppDatabase.getInstance(getContext()); } }
Key Notes
- If you need to modify existing tables (not just add new ones), you’ll need to write manual SQL migration statements in
onUpgrade—Schematic doesn’t auto-generate alter table commands, so you’ll have to handle that yourself. - Make sure you only run each migration once by checking the
oldVersionagainst the new version (this way, users jumping from v1 to v3 will run all necessary migrations).
内容的提问来源于stack exchange,提问作者Kanchan

