A helper class to manage database creation and version management.
數(shù)據(jù)庫的創(chuàng)建和版本管理的助手。
SQLiteOpenHelper 是一個抽象類,abstract class.
擁有成員變量,mName(數(shù)據(jù)庫名稱),mNewVersion(數(shù)據(jù)庫版本),mDatabase(數(shù)據(jù)庫)等.
構造函數(shù)需要傳遞,context,數(shù)據(jù)庫名稱,數(shù)據(jù)庫版本等信息.
SQLiteOpenHelper(Context context, String name, CursorFactory factory,int version)
實現(xiàn)了以下函數(shù):
getDatabaseName
getWritableDatabase
getReadableDatabase
onDowngrade
close
subclass需要實現(xiàn)以下函數(shù):
public abstract void onCreate(SQLiteDatabase db);
public abstract void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion);
面試題1
使用SQLiteOpenHelper的getReadableDatabase()獲得的數(shù)據(jù)庫能不能,做寫的操作
能
面試題2
寫一個子類繼承SQLiteOpenHelper,并實現(xiàn)以下功能
1).創(chuàng)建一個版本為1的“diaryOpenHelper.db”的數(shù)據(jù)庫,
2).同時創(chuàng)建一個 “diary” 表(包含一個_id主鍵并自增長,topic字符型100長度, content字符型1000長度)
3).在數(shù)據(jù)庫版本變化時請刪除diary表,并重新創(chuàng)建出diary表
publicclass DBHelper extends SQLiteOpenHelper{
public final static String DATABASENAME ="diaryOpenHelper.db";
public final static int DATABASEVERSION =1;//創(chuàng)建數(shù)據(jù)庫
public DBHelper(Context context,Stringname,CursorFactory factory,int version)
{
super(context, name, factory,version);
}//創(chuàng)建表等機構性文件
public void onCreate(SQLiteDatabase db)
{
String sql ="create table diary"+"("+"_id integer primary key autoincrement,"+"topic varchar(100),"+"content varchar(1000)"+")";
db.execSQL(sql);
}//若數(shù)據(jù)庫版本有更新,則調用此方法
public void onUpgrade(SQLiteDatabasedb,int oldVersion,int newVersion)
{
String sql = "drop table if exists diary";
db.execSQL(sql);
this.onCreate(db);
}
}
文末
歡迎關注我的簡書,分享Android干貨,交流Android技術。
對文章有何見解,或者有何技術問題,都可以在評論區(qū)一起留言討論,我會虔誠為你解答。
最后,如果你想知道更多Android的知識或需要其他資料我這里均免費分享,只需你點贊+評論找我獲取哦