升级数据库
如果我们想再添加一个表到我们创建的数据库BookStore.db中不能像创建第一个表book时那样简单的写到oncreate方法中了,因为我们的数据库已经创建了,onCreate()不会再执行了,所以就用到了onUpgrade()方法。
可以将MyDatabaseHelper改为:
1 package ga.orlion.databasedemo; 2 3 4 5 import android.content.Context; 6 7 import android.database.sqlite.SQLiteDatabase; 8 9 import android.database.sqlite.SQLiteDatabase.CursorFactory; 10 11 import android.widget.Toast; 12 13 import android.database.sqlite.SQLiteOpenHelper; 14 15 16 17 public class MyDatabaseHelper extends SQLiteOpenHelper { 18 19 20 public static final String CREATE_BOOK = "create table book (" 21 22 + "id integer primary key autoincrement, " 23 24 + "author text, " 25 26 + "price real, " 27 28 + "pages integer, " 29 30 + "name text)"; 31 32 33 34 public static final String CREATE_CATEGORY = "create table Category (" 35 36 + "id integer primary key autoincrement, " 37 38 + "category_name text, " 39 40 + "category_code integer)"; 41 42 43 44 private Context mContext; 45 46 47 48 public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version) { 49 50 super(context, name, factory, version); 51 52 mContext = context; 53 54 } 55 56 @Override 57 58 public void onCreate(SQLiteDatabase db) { 59 60 61 62 db.execSQL(CREATE_BOOK); 63 64 db.execSQL(CREATE_CATEGORY); 65 66 Toast.makeText(mContext, "数据库创建了", Toast.LENGTH_SHORT).show(); 67 68 } 69 70 71 72 @Override 73 74 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 75 76 db.execSQL("drop table if exists Book"); 77 78 db.execSQL("drop table if exists Category"); 79 80 onCreate(db); 81 82 } 83 84 85 86 }
可以看到,我们在 onUpgrade()方法中执行了两条 DROP语句,如果发现数据库中已经存在 Book表或 Category表了,就将这两张表删除掉,然后再调用 onCreate()方法去重新创建。这里先将已经存在的表删除掉,是因为如果在创建表时发现这张表已经存在了,就会直接报错。