加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

SQLite

发布时间:2020-12-12 23:57:59 所属栏目:百科 来源:网络整理
导读:DBHelper继承了SQLiteOpenHelper,作为维护和管理数据库的基类,DBManager是建立在DBHelper之上,封装了常用的业务方法,Person是我们的person表对应的JavaBean,MainActivity就是我们显示的界面。 下面我们先来看一下DBHelper: [java] view plain copy pac

DBHelper继承了SQLiteOpenHelper,作为维护和管理数据库的基类,DBManager是建立在DBHelper之上,封装了常用的业务方法,Person是我们的person表对应的JavaBean,MainActivity就是我们显示的界面。

下面我们先来看一下DBHelper:

[java] view plain copy
  1. packagecom.scott.db;
  2. importandroid.content.Context;
  3. importandroid.database.sqlite.SQLiteDatabase;
  4. importandroid.database.sqlite.SQLiteOpenHelper;
  5. publicclassDBHelperextendsSQLiteOpenHelper{
  6. privatestaticfinalStringDATABASE_NAME="test.db";
  7. finalintDATABASE_VERSION=1;
  8. publicDBHelper(Contextcontext){
  9. //CursorFactory设置为null,使用默认值
  10. super(context,DATABASE_NAME,null,DATABASE_VERSION);
  11. }
  12. //数据库第一次被创建时onCreate会被调用
  13. @Override
  14. voidonCreate(SQLiteDatabasedb){
  15. db.execSQL("CREATETABLEIFNOTEXISTSperson"+
  16. "(_idINTEGERPRIMARYKEYAUTOINCREMENT,nameVARCHAR,ageINTEGER,infoTEXT)");
  17. }
  18. //如果DATABASE_VERSION值被改为2,系统发现现有数据库版本不同,即会调用onUpgrade
  19. @Override
  20. voidonUpgrade(SQLiteDatabasedb,153); background-color:inherit; font-weight:bold">intoldVersion,153); background-color:inherit; font-weight:bold">intnewVersion){
  21. db.execSQL("ALTERTABLEpersonADDCOLUMNotherSTRING");
  22. }
正如上面所述,数据库第一次创建时onCreate方法会被调用,我们可以执行创建表的语句,当系统发现版本变化之后,会调用onUpgrade方法,我们可以执行修改表结构等语句。

为了方便我们面向对象的使用数据,我们建一个Person类,对应person表中的字段,如下:

copy
    classPerson{
  1. int_id;
  2. publicStringname;
  3. intage;
  4. publicStringinfo;
  5. publicPerson(){
  6. publicPerson(Stringname,153); background-color:inherit; font-weight:bold">intage,Stringinfo){
  7. this.name=name;
  8. this.age=age;
  9. this.info=info;
  10. }
然后,我们需要一个DBManager,来封装我们所有的业务方法,代码如下:

copy
    importjava.util.ArrayList;
  1. importjava.util.List;
  2. importandroid.content.ContentValues;
  3. importandroid.database.Cursor;
  4. importandroid.database.sqlite.SQLiteDatabase;
  5. classDBManager{
  6. privateDBHelperhelper;
  7. privateSQLiteDatabasedb;
  8. publicDBManager(Contextcontext){
  9. helper=newDBHelper(context);
  10. //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName,mFactory);
  11. //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
  12. db=helper.getWritableDatabase();
  13. /**
  14. *addpersons
  15. *@parampersons
  16. */
  17. voidadd(List<Person>persons){
  18. db.beginTransaction();//开始事务
  19. try{
  20. for(Personperson:persons){
  21. db.execSQL("INSERTINTOpersonVALUES(null,?,?)",153); background-color:inherit; font-weight:bold">newObject[]{person.name,person.age,person.info});
  22. db.setTransactionSuccessful();//设置事务成功完成
  23. }finally{
  24. db.endTransaction();//结束事务
  25. *updateperson'sage
  26. *@paramperson
  27. voidupdateAge(Personperson){
  28. ContentValuescv=newContentValues();
  29. cv.put("age",person.age);
  30. db.update("person",cv,"name=?",153); background-color:inherit; font-weight:bold">newString[]{person.name});
  31. *deleteoldperson
  32. voiddeleteOldPerson(Personperson){
  33. db.delete("person","age>=?",153); background-color:inherit; font-weight:bold">newString[]{String.valueOf(person.age)});
  34. *queryallpersons,returnlist
  35. *@returnList<Person>
  36. publicList<Person>query(){
  37. ArrayList<Person>persons=newArrayList<Person>();
  38. Cursorc=queryTheCursor();
  39. while(c.moveToNext()){
  40. Personperson=newPerson();
  41. person._id=c.getInt(c.getColumnIndex("_id"));
  42. person.name=c.getString(c.getColumnIndex("name"));
  43. person.age=c.getInt(c.getColumnIndex("age"));
  44. person.info=c.getString(c.getColumnIndex("info"));
  45. persons.add(person);
  46. c.close();
  47. returnpersons;
  48. /**
  49. *@returnCursor
  50. */
  51. publicCursorqueryTheCursor(){
  52. Cursorc=db.rawQuery("SELECT*FROMperson",153); background-color:inherit; font-weight:bold">null);
  53. returnc;
  54. *closedatabase
  55. voidcloseDB(){
  56. db.close();
  57. }
我们在DBManager构造方法中实例化DBHelper并获取一个SQLiteDatabase对象,作为整个应用的数据库实例;在添加多个Person信息时,我们采用了事务处理,确保数据完整性;最后我们提供了一个closeDB方法,释放数据库资源,这一个步骤在我们整个应用关闭时执行,这个环节容易被忘记,所以朋友们要注意。

我们获取数据库实例时使用了getWritableDatabase()方法,也许朋友们会有疑问,在getWritableDatabase()和getReadableDatabase()中,你为什么选择前者作为整个应用的数据库实例呢?在这里我想和大家着重分析一下这一点。

我们来看一下SQLiteOpenHelper中的getReadableDatabase()方法:

copy
    synchronizedSQLiteDatabasegetReadableDatabase(){
  1. if(mDatabase!=null&&mDatabase.isOpen()){
  2. //如果发现mDatabase不为空并且已经打开则直接返回
  3. returnmDatabase;
  4. if(mIsInitializing){
  5. //如果正在初始化则抛出异常
  6. thrownewIllegalStateException("getReadableDatabasecalledrecursively");
  7. //开始实例化数据库mDatabase
  8. //注意这里是调用了getWritableDatabase()方法
  9. returngetWritableDatabase();
  10. catch(SQLiteExceptione){
  11. if(mName==null)
  12. throwe;//Can'topenatempdatabaseread-only!
  13. Log.e(TAG,"Couldn'topen"+mName+"forwriting(willtryread-only):",e);
  14. //如果无法以可读写模式打开数据库则以只读方式打开
  15. SQLiteDatabasedb=null;
  16. mIsInitializing=true;
  17. Stringpath=mContext.getDatabasePath(mName).getPath();//获取数据库路径
  18. //以只读方式打开数据库
  19. db=SQLiteDatabase.openDatabase(path,mFactory,SQLiteDatabase.OPEN_READONLY);
  20. if(db.getVersion()!=mNewVersion){
  21. newSQLiteException("Can'tupgraderead-onlydatabasefromversion"+db.getVersion()+"to"
  22. +mNewVersion+":"+path);
  23. onOpen(db);
  24. Log.w(TAG,"Opened"+mName+"inread-onlymode");
  25. mDatabase=db;//为mDatabase指定新打开的数据库
  26. returnmDatabase;//返回打开的数据库
  27. }finally{
  28. false;
  29. if(db!=null&&db!=mDatabase)
  30. db.close();
  31. }
在getReadableDatabase()方法中,首先判断是否已存在数据库实例并且是打开状态,如果是,则直接返回该实例,否则试图获取一个可读写模式的数据库实例,如果遇到磁盘空间已满等情况获取失败的话,再以只读模式打开数据库,获取数据库实例并返回,然后为mDatabase赋值为最新打开的数据库实例。既然有可能调用到getWritableDatabase()方法,我们就要看一下了:

copy
    synchronizedSQLiteDatabasegetWritableDatabase(){
  1. null&&mDatabase.isOpen()&&!mDatabase.isReadOnly()){
  2. //如果mDatabase不为空已打开并且不是只读模式则返回该实例
  3. newIllegalStateException("getWritableDatabasecalledrecursively");
  4. //Ifwehavearead-onlydatabaSEOpen,someonecouldbeusingit
  5. //(thoughtheyshouldn't),whichwouldcausealocktobeheldon
  6. //thefile,andourattemptstoopenthedatabaseread-writewould
  7. //failwaitingforthefilelock.Topreventthat,weacquirethe
  8. //lockontheread-onlydatabase,whichshutsoutotherusers.
  9. booleansuccess= SQLiteDatabasedb=null;
  10. //如果mDatabase不为空则加锁阻止其他的操作
  11. mDatabase.lock();
  12. null){
  13. db=SQLiteDatabase.create(null);
  14. else{
  15. //打开或创建数据库
  16. db=mContext.openOrCreateDatabase(mName,0,mFactory);
  17. //获取数据库版本(如果刚创建的数据库,版本为0)
  18. intversion=db.getVersion();
  19. //比较版本(我们代码中的版本mNewVersion为1)
  20. if(version!=mNewVersion){
  21. db.beginTransaction();//开始事务
  22. try{
  23. if(version==0){
  24. //执行我们的onCreate方法
  25. onCreate(db);
  26. else{
  27. //如果我们应用升级了mNewVersion为2,而原版本为1则执行onUpgrade方法
  28. onUpgrade(db,version,mNewVersion);
  29. db.setVersion(mNewVersion);//设置最新版本
  30. //设置事务成功
  31. success=returndb;//返回可读写模式的数据库实例
  32. mIsInitializing=false;
  33. if(success){
  34. //打开成功
  35. null){
  36. //如果mDatabase有值则先关闭
  37. mDatabase.close();
  38. catch(Exceptione){
  39. mDatabase.unlock();//解锁
  40. mDatabase=db;//赋值给mDatabase
  41. //打开失败的情况:解锁、关闭
  42. mDatabase.unlock();
  43. }
大家可以看到,几个关键步骤是,首先判断mDatabase如果不为空已打开并不是只读模式则直接返回,否则如果mDatabase不为空则加锁,然后开始打开或创建数据库,比较版本,根据版本号来调用相应的方法,为数据库设置新版本号,最后释放旧的不为空的mDatabase并解锁,把新打开的数据库实例赋予mDatabase,并返回最新实例。

看完上面的过程之后,大家或许就清楚了许多,如果不是在遇到磁盘空间已满等情况,getReadableDatabase()一般都会返回和getWritableDatabase()一样的数据库实例,所以我们在DBManager构造方法中使用getWritableDatabase()获取整个应用所使用的数据库实例是可行的。当然如果你真的担心这种情况会发生,那么你可以先用getWritableDatabase()获取数据实例,如果遇到异常,再试图用getReadableDatabase()获取实例,当然这个时候你获取的实例只能读不能写了。

最后,让我们看一下如何使用这些数据操作方法来显示数据,下面是MainActivity.java的布局文件和代码:

[html] copy
    <?xmlversion="1.0"encoding="utf-8"?>
  1. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  2. android:orientation="vertical"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. Button
  6. android:layout_width="fill_parent"
  7. android:layout_height="wrap_content"
  8. android:text="add"
  9. android:onClick="add"/>
  10. Button
  11. android:layout_height="wrap_content"
  12. android:text="update"
  13. android:onClick="update"/>
  14. android:text="delete"
  15. android:onClick="delete" android:text="query"
  16. android:onClick="query" android:text="queryTheCursor"
  17. android:onClick="queryTheCursor"ListView
  18. android:id="@+id/listView"
  19. android:layout_height="wrap_content"</LinearLayout>

copy
    importjava.util.HashMap;
  1. importjava.util.List;
  2. importjava.util.Map;
  3. importandroid.app.Activity;
  4. importandroid.database.Cursor;
  5. importandroid.database.CursorWrapper;
  6. importandroid.os.Bundle;
  7. importandroid.view.View;
  8. importandroid.widget.ListView;
  9. importandroid.widget.SimpleAdapter;
  10. importandroid.widget.SimpleCursorAdapter;
  11. classMainActivityextendsActivity{
  12. privateDBManagermgr;
  13. privateListViewlistView;
  14. voidonCreate(BundlesavedInstanceState){
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.main);
  17. listView=(ListView)findViewById(R.id.listView);
  18. //初始化DBManager
  19. mgr=newDBManager(this);
  20. protectedvoidonDestroy(){
  21. super.onDestroy();
  22. //应用的最后一个Activity关闭时应释放DB
  23. mgr.closeDB();
  24. voidadd(Viewview){
  25. ArrayList<Person>persons=newArrayList<Person>();
  26. Personperson1=newPerson("Ella",22,"livelygirl");
  27. Personperson2=newPerson("Jenny","beautifulgirl");
  28. Personperson3=newPerson("Jessica",0); background-color:inherit">23,"sexygirl");
  29. Personperson4=newPerson("Kelly","hotbaby");
  30. Personperson5=newPerson("Jane",0); background-color:inherit">25,"aprettywoman");
  31. persons.add(person1);
  32. persons.add(person2);
  33. persons.add(person3);
  34. persons.add(person4);
  35. persons.add(person5);
  36. mgr.add(persons);
  37. voidupdate(Viewview){
  38. person.name="Jane";
  39. person.age=30;
  40. mgr.updateAge(person);
  41. voiddelete(Viewview){
  42. Personperson=newPerson();
  43. mgr.deleteOldPerson(person);
  44. voidquery(Viewview){
  45. List<Person>persons=mgr.query();
  46. ArrayList<Map<String,String>>list=newArrayList<Map<String,String>>();
  47. HashMap<String,String>map=newHashMap<String,String>();
  48. map.put("name",person.name);
  49. map.put("info",person.age+"yearsold,"+person.info);
  50. list.add(map);
  51. SimpleAdapteradapter=newSimpleAdapter(this,list,android.R.layout.simple_list_item_2,
  52. newString[]{"name","info"},153); background-color:inherit; font-weight:bold">newint[]{android.R.id.text1,android.R.id.text2});
  53. listView.setAdapter(adapter);
  54. voidqueryTheCursor(Viewview){
  55. Cursorc=mgr.queryTheCursor();
  56. startManagingCursor(c);//托付给activity根据自己的生命周期去管理Cursor的生命周期
  57. CursorWrappercursorWrapper=newCursorWrapper(c){
  58. publicStringgetString(intcolumnIndex){
  59. //将简介前加上年龄
  60. if(getColumnName(columnIndex).equals("info")){
  61. intage=getInt(getColumnIndex("age"));
  62. returnage+"yearsold,"+super.getString(columnIndex);
  63. return };
  64. //确保查询结果中有"_id"列
  65. SimpleCursorAdapteradapter=newSimpleCursorAdapter( cursorWrapper, ListViewlistView=(ListView)findViewById(R.id.listView);
  66. listView.setAdapter(adapter);
  67. }
这里需要注意的是SimpleCursorAdapter的应用,当我们使用这个适配器时,我们必须先得到一个Cursor对象,这里面有几个问题:如何管理Cursor的生命周期,如果包装Cursor,Cursor结果集都需要注意什么。

如果手动去管理Cursor的话会非常的麻烦,还有一定的风险,处理不当的话运行期间就会出现异常,幸好Activity为我们提供了startManagingCursor(Cursor cursor)方法,它会根据Activity的生命周期去管理当前的Cursor对象,下面是该方法的说明:

copy
    *Thismethodallowstheactivitytotakecareofmanagingthegiven
  1. *{@linkCursor}'slifecycleforyoubasedontheactivity'slifecycle.
  2. *Thatis,whentheactivityisstoppeditwillautomaticallycall
  3. *{@linkCursor#deactivate}onthegivenCursor,andwhenitislaterrestarted
  4. *itwillcall{@linkCursor#requery}foryou.Whentheactivityis
  5. *destroyed,allmanagedCursorswillbeclosedautomatically.
  6. *
  7. *@paramcTheCursortobemanaged.
  8. *@see#managedQuery(android.net.Uri,String[],String,String)
  9. *@see#stopManagingCursor
  10. */
文中提到,startManagingCursor方法会根据Activity的生命周期去管理当前的Cursor对象的生命周期,就是说当Activity停止时他会自动调用Cursor的deactivate方法,禁用游标,当Activity重新回到屏幕时它会调用Cursor的requery方法再次查询,当Activity摧毁时,被管理的Cursor都会自动关闭释放。

如何包装Cursor:我们会使用到CursorWrapper对象去包装我们的Cursor对象,实现我们需要的数据转换工作,这个CursorWrapper实际上是实现了Cursor接口。我们查询获取到的Cursor其实是Cursor的引用,而系统实际返回给我们的必然是Cursor接口的一个实现类的对象实例,我们用CursorWrapper包装这个实例,然后再使用SimpleCursorAdapter将结果显示到列表上。

Cursor结果集需要注意些什么:一个最需要注意的是,在我们的结果集中必须要包含一个“_id”的列,否则SimpleCursorAdapter就会翻脸不认人,为什么一定要这样呢?因为这源于SQLite的规范,主键以“_id”为标准。解决办法有三:第一,建表时根据规范去做;第二,查询时用别名,例如:SELECT id AS _id FROM person;第三,在CursorWrapper里做文章:

copy
    CursorWrappercursorWrapper=intgetColumnIndexOrThrow(StringcolumnName)throwsIllegalArgumentException{
  1. if(columnName.equals("_id")){
  2. super.getColumnIndex("id");
  3. super.getColumnIndexOrThrow(columnName);
  4. };
如果试图从CursorWrapper里获取“_id”对应的列索引,我们就返回查询结果里“id”对应的列索引即可。

最后我们来看一下结果如何:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读