zoukankan      html  css  js  c++  java
  • SQLite详解

    通过一个实例来分析..(转自http://blog.csdn.net/liuhe688/article/details/6715983,很好很强大,我根据自己需要摘取其中一部,稍作改动之后程序可运行)

    step1: 新建工程TestSQLite2,结构图如下

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

    step2:

    (1)展示MyHelper

    MyHelper
     1 package com.cb.sqlite2;
     2 
     3 import android.content.Context;
     4 import android.database.sqlite.SQLiteDatabase;
     5 import android.database.sqlite.SQLiteOpenHelper;
     6 
     7 public class MyHelper extends SQLiteOpenHelper{
     8     private static final String DATABASE_NAME = "test.db";
     9     private static final int DATABASE_VERSION = 1;
    10     
    11     //在SQLiteOpenHelper的子类中,必须有构造函数
    12     public MyHelper(Context context) {
    13         //必须调用父类的构造函数
    14         super(context, DATABASE_NAME, null, DATABASE_VERSION);
    15     }
    16     
    17     //该函数在第一次创建数据库的时候执行,实际上是在第一次得到SQLiteDatabase对象的时候,才会调用这个方法
    18     @Override
    19     public void onCreate(SQLiteDatabase db) {
    20         db.execSQL("create table if not exists person (id int, name varchar(20), age int, info varchar(20))");
    21     }
    22     
    23     //如果DATABASE_VERSION值被改为2,系统发现现有数据库版本不同,即会调用onUpgrade
    24     @Override
    25     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    26     }
    27 
    28 }

    如上面所述,数据库第一次创建时onCreate方法会被调用,我们可以执行创建表的语句,当系统发现版本变化之后,会调用onUpgrade方法,我们可以执行修改表结构等语句。

    (2)展示Person类

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

    Person
     1 package com.cb.sqlite2;
     2 
     3 public class Person {
     4     public int id;
     5     public String name;
     6     public int age;
     7     public String info;
     8     
     9     public Person() {
    10     }
    11     
    12     public Person(int id, String name, int age, String info) {
    13         this.id = id;
    14         this.name = name;
    15         this.age = age;
    16         this.info = info;
    17     }
    18 
    19     public int getId() {
    20         return id;
    21     }
    22 
    23     public void setId(int id) {
    24         this.id = id;
    25     }
    26 
    27     public String getName() {
    28         return name;
    29     }
    30 
    31     public void setName(String name) {
    32         this.name = name;
    33     }
    34 
    35     public int getAge() {
    36         return age;
    37     }
    38 
    39     public void setAge(int age) {
    40         this.age = age;
    41     }
    42     
    43     public String getInfo() {
    44         return info;
    45     }
    46 
    47     public void setInfo(String info) {
    48         this.info = info;
    49     }
    50     
    51 }

    (3)展示DBManager

    通过DBManager,来封装我们所有的业务方法:

    DBManager
     1 package com.cb.sqlite2;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 import android.content.ContentValues;
     7 import android.content.Context;
     8 import android.database.Cursor;
     9 import android.database.sqlite.SQLiteDatabase;
    10 
    11 public class DBManager {
    12     private MyHelper helper;
    13     private SQLiteDatabase db;
    14     
    15     public DBManager(Context context) {
    16         helper = new MyHelper(context);
    17         //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);
    18         //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
    19         db = helper.getWritableDatabase();
    20     }
    21     
    22     /**
    23      * add persons
    24      * @param persons
    25      */
    26     public void add(List<Person> persons) {
    27         db.beginTransaction();    //开始事务
    28         try {
    29             for (Person person : persons) {
    30                 db.execSQL("insert into person values(?, ?, ?, ?)", new Object[]{person.id, person.name, person.age, person.info});
    31             }
    32             db.setTransactionSuccessful();    //设置事务成功完成
    33         } finally {
    34             db.endTransaction();    //结束事务
    35         }
    36     }
    37     
    38     /**
    39      * update person's age
    40      * @param person
    41      */
    42     public void updateAge(Person person) {
    43         ContentValues cv = new ContentValues();
    44         cv.put("age", person.age);
    45         db.update("person", cv, "name = ?", new String[]{person.name});
    46     }
    47     
    48     /**
    49      * delete old person
    50      * @param person
    51      */
    52     public void deleteOldPerson(Person person) {
    53         db.delete("person", "age >= ?", new String[]{String.valueOf(person.age)});
    54     }
    55     
    56     /**
    57      * query all persons, return list
    58      * @return List<Person>
    59      */
    60     public List<Person> query() {
    61         ArrayList<Person> persons = new ArrayList<Person>();
    62         Cursor c = queryTheCursor();
    63         while (c.moveToNext()) {
    64             Person person = new Person();
    65             person.id = c.getInt(c.getColumnIndex("id"));
    66             person.name = c.getString(c.getColumnIndex("name"));
    67             person.age = c.getInt(c.getColumnIndex("age"));
    68             person.info = c.getString(c.getColumnIndex("info"));
    69             persons.add(person);
    70         }
    71         c.close();
    72         return persons;
    73     }
    74     
    75     /**
    76      * query all persons, return cursor
    77      * @return    Cursor
    78      */
    79     public Cursor queryTheCursor() {
    80         Cursor c = db.rawQuery("select * from person", null);
    81         return c;
    82     }
    83     
    84     /**
    85      * close database
    86      */
    87     public void closeDB() {
    88         db.close();
    89     }
    90 }

    我们在DBManager构造方法中实例化DBHelper并获取一个SQLiteDatabase对象,作为整个应用的数据库实例;在添加多个Person信息时,我们采用了事务处理,确保数据完整性;最后我们提供了一个closeDB方法,释放数据库资源,这一个步骤在我们整个应用关闭时执行,这个环节容易被忘记,所以朋友们要注意。

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

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

    getReadableDatabase
     1     public synchronized SQLiteDatabase getReadableDatabase() {
     2         if (mDatabase != null && mDatabase.isOpen()) {
     3             // 如果发现mDatabase不为空并且已经打开则直接返回
     4             return mDatabase;
     5         }
     6 
     7         if (mIsInitializing) {
     8             // 如果正在初始化则抛出异常
     9             throw new IllegalStateException("getReadableDatabase called recursively");
    10         }
    11 
    12         // 开始实例化数据库mDatabase
    13 
    14         try {
    15             // 注意这里是调用了getWritableDatabase()方法
    16             return getWritableDatabase();
    17         } catch (SQLiteException e) {
    18             if (mName == null)
    19                 throw e; // Can't open a temp database read-only!
    20             Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
    21         }
    22 
    23         // 如果无法以可读写模式打开数据库 则以只读方式打开
    24 
    25         SQLiteDatabase db = null;
    26         try {
    27             mIsInitializing = true;
    28             String path = mContext.getDatabasePath(mName).getPath();// 获取数据库路径
    29             // 以只读方式打开数据库
    30             db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
    31             if (db.getVersion() != mNewVersion) {
    32                 throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to "
    33                         + mNewVersion + ": " + path);
    34             }
    35 
    36             onOpen(db);
    37             Log.w(TAG, "Opened " + mName + " in read-only mode");
    38             mDatabase = db;// 为mDatabase指定新打开的数据库
    39             return mDatabase;// 返回打开的数据库
    40         } finally {
    41             mIsInitializing = false;
    42             if (db != null && db != mDatabase)
    43                 db.close();
    44         }
    45     }

    在getReadableDatabase()方法中,首先判断是否已存在数据库实例并且是打开状态,如果是,则直接返回该实例,否则试图获取一个可读写模式的数据库实例,如果遇到磁盘空间已满等情况获取失败的话,再以只读模式打开数据库,获取数据库实例并返回,然后为mDatabase赋值为最新打开的数据库实例。既然有可能调用到getWritableDatabase()方法,我们就要看一下了:

    getWritableDatabase
     1     public synchronized SQLiteDatabase getWritableDatabase() {
     2         if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
     3             // 如果mDatabase不为空已打开并且不是只读模式 则返回该实例
     4             return mDatabase;
     5         }
     6 
     7         if (mIsInitializing) {
     8             throw new IllegalStateException("getWritableDatabase called recursively");
     9         }
    10 
    11         // If we have a read-only database open, someone could be using it
    12         // (though they shouldn't), which would cause a lock to be held on
    13         // the file, and our attempts to open the database read-write would
    14         // fail waiting for the file lock. To prevent that, we acquire the
    15         // lock on the read-only database, which shuts out other users.
    16 
    17         boolean success = false;
    18         SQLiteDatabase db = null;
    19         // 如果mDatabase不为空则加锁 阻止其他的操作
    20         if (mDatabase != null)
    21             mDatabase.lock();
    22         try {
    23             mIsInitializing = true;
    24             if (mName == null) {
    25                 db = SQLiteDatabase.create(null);
    26             } else {
    27                 // 打开或创建数据库
    28                 db = mContext.openOrCreateDatabase(mName, 0, mFactory);
    29             }
    30             // 获取数据库版本(如果刚创建的数据库,版本为0)
    31             int version = db.getVersion();
    32             // 比较版本(我们代码中的版本mNewVersion为1)
    33             if (version != mNewVersion) {
    34                 db.beginTransaction();// 开始事务
    35                 try {
    36                     if (version == 0) {
    37                         // 执行我们的onCreate方法
    38                         onCreate(db);
    39                     } else {
    40                         // 如果我们应用升级了mNewVersion为2,而原版本为1则执行onUpgrade方法
    41                         onUpgrade(db, version, mNewVersion);
    42                     }
    43                     db.setVersion(mNewVersion);// 设置最新版本
    44                     db.setTransactionSuccessful();// 设置事务成功
    45                 } finally {
    46                     db.endTransaction();// 结束事务
    47                 }
    48             }
    49 
    50             onOpen(db);
    51             success = true;
    52             return db;// 返回可读写模式的数据库实例
    53         } finally {
    54             mIsInitializing = false;
    55             if (success) {
    56                 // 打开成功
    57                 if (mDatabase != null) {
    58                     // 如果mDatabase有值则先关闭
    59                     try {
    60                         mDatabase.close();
    61                     } catch (Exception e) {
    62                     }
    63                     mDatabase.unlock();// 解锁
    64                 }
    65                 mDatabase = db;// 赋值给mDatabase
    66             } else {
    67                 // 打开失败的情况:解锁、关闭
    68                 if (mDatabase != null)
    69                     mDatabase.unlock();
    70                 if (db != null)
    71                     db.close();
    72             }
    73         }
    74     }

    大家可以看到,几个关键步骤是,首先判断mDatabase如果不为空已打开并不是只读模式则直接返回,否则如果mDatabase不为空则加锁,然后开始打开或创建数据库,比较版本,根据版本号来调用相应的方法,为数据库设置新版本号,最后释放旧的不为空的mDatabase并解锁,把新打开的数据库实例赋予mDatabase,并返回最新实例。

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

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

    (4)展示TestSQLite2.java和布局文件

    main.xml
     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:orientation="vertical"
     4     android:layout_width="fill_parent"
     5     android:layout_height="fill_parent">
     6     <Button
     7         android:layout_width="fill_parent"
     8         android:layout_height="wrap_content"
     9         android:text="add"
    10         android:onClick="add"/>
    11     <Button
    12         android:layout_width="fill_parent"
    13         android:layout_height="wrap_content"
    14         android:text="update"
    15         android:onClick="update"/>
    16     <Button
    17         android:layout_width="fill_parent"
    18         android:layout_height="wrap_content"
    19         android:text="delete"
    20         android:onClick="delete"/>
    21     <Button
    22         android:layout_width="fill_parent"
    23         android:layout_height="wrap_content"
    24         android:text="query"
    25         android:onClick="query"/>
    26     <Button
    27         android:layout_width="fill_parent"
    28         android:layout_height="wrap_content"
    29         android:text="queryTheCursor"
    30         android:onClick="queryTheCursor"/>
    31     <ListView
    32         android:id="@+id/listView"
    33         android:layout_width="fill_parent"
    34         android:layout_height="wrap_content"/>
    35 </LinearLayout>
    TestSQLite2
      1 package com.cb.sqlite2;
      2 
      3 
      4 import java.util.ArrayList;
      5 import java.util.HashMap;
      6 import java.util.List;
      7 import java.util.Map;
      8 
      9 import android.app.Activity;
     10 import android.database.Cursor;
     11 import android.database.CursorWrapper;
     12 import android.os.Bundle;
     13 import android.view.View;
     14 import android.widget.ListView;
     15 import android.widget.SimpleAdapter;
     16 import android.widget.SimpleCursorAdapter;
     17 
     18 public class TestSQLite2 extends Activity {
     19    
     20     private DBManager mgr;
     21     private ListView listView;
     22     
     23     @Override
     24     public void onCreate(Bundle savedInstanceState) {
     25         super.onCreate(savedInstanceState);
     26         setContentView(R.layout.main);
     27         listView = (ListView) findViewById(R.id.listView);
     28         //初始化DBManager
     29         mgr = new DBManager(this);
     30     }
     31     
     32     @Override
     33     protected void onDestroy() {
     34         super.onDestroy();
     35         //应用的最后一个Activity关闭时应释放DB
     36         mgr.closeDB();
     37     }
     38     
     39     public void add(View view) {
     40         ArrayList<Person> persons = new ArrayList<Person>();
     41         
     42         Person person1 = new Person(1, "Ella", 22, "lively girl");
     43         Person person2 = new Person(2, "Jenny", 22, "beautiful girl");
     44         Person person3 = new Person(3, "Jessica", 23, "sexy girl");
     45         Person person4 = new Person(4, "Kelly", 23, "hot baby");
     46         Person person5 = new Person(5, "Jane", 25, "a pretty woman");
     47         
     48         persons.add(person1);
     49         persons.add(person2);
     50         persons.add(person3);
     51         persons.add(person4);
     52         persons.add(person5);
     53         
     54         mgr.add(persons);
     55     }
     56     
     57     public void update(View view) {
     58         Person person = new Person();
     59         person.name = "Jane";
     60         person.age = 30;
     61         mgr.updateAge(person);
     62     }
     63     
     64     public void delete(View view) {
     65         Person person = new Person();
     66         person.age = 30;
     67         mgr.deleteOldPerson(person);
     68     }
     69     
     70     public void query(View view) {
     71         List<Person> persons = mgr.query();
     72         ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
     73         for (Person person : persons) {
     74             HashMap<String, String> map = new HashMap<String, String>();
     75             map.put("name", person.name);
     76             map.put("info", person.age + " years old, " + person.info);
     77             list.add(map);
     78         }
     79         SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2,
     80                     new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2});
     81         listView.setAdapter(adapter);
     82     }
     83     
     84     public void queryTheCursor(View view) {
     85         Cursor c = mgr.queryTheCursor();
     86         startManagingCursor(c);    //托付给activity根据自己的生命周期去管理Cursor的生命周期
     87         CursorWrapper cursorWrapper = new CursorWrapper(c) {
     88             @Override
     89             public String getString(int columnIndex) {
     90                 //将简介前加上年龄
     91                 if (getColumnName(columnIndex).equals("info")) {
     92                     int age = getInt(getColumnIndex("age"));
     93                     return age + " years old, " + super.getString(columnIndex);
     94                 }
     95                 return super.getString(columnIndex);
     96             }
     97             
     98             public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {  
     99                 if (columnName.equals("_id")) {  
    100                     return super.getColumnIndex("id");  
    101                 }  
    102                 return super.getColumnIndexOrThrow(columnName);  
    103             }  
    104             
    105             
    106         };
    107         //确保查询结果中有"id"列
    108         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, 
    109                 cursorWrapper, new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2});
    110         ListView listView = (ListView) findViewById(R.id.listView);
    111         listView.setAdapter(adapter);
    112     }
    113 }

    这里需要注意的是SimpleCursorAdapter的应用,当我们使用这个适配器时,我们必须先得到一个Cursor对象,这里面有几个问题:如何管理Cursor的生命周期,如果包装Cursor,Cursor结果集都需要注意什么。

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

     1 /**
     2      * This method allows the activity to take care of managing the given
     3      * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
     4      * That is, when the activity is stopped it will automatically call
     5      * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
     6      * it will call {@link Cursor#requery} for you.  When the activity is
     7      * destroyed, all managed Cursors will be closed automatically.
     8      * 
     9      * @param c The Cursor to be managed.
    10      * 
    11      * @see #managedQuery(android.net.Uri , String[], String, String[], String)
    12      * @see #stopManagingCursor
    13      */

    文中提到,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里做文章:

    1         CursorWrapper cursorWrapper = new CursorWrapper(c) {
    2             @Override
    3             public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
    4                 if (columnName.equals("_id")) {
    5                     return super.getColumnIndex("id");
    6                 }
    7                 return super.getColumnIndexOrThrow(columnName);
    8             }
    9         };

    如果试图从CursorWrapper里获取“_id”对应的列索引,我们就返回查询结果里“id”对应的列索引即可。

    step3:查看结果

     

  • 相关阅读:
    BZOJ 1449: [JSOI2009]球队收益 最小费用最大流 网络流
    HDU 4348 To the moon 主席树 在线更新
    省选模拟赛20180416
    线性基总结
    Write-up-Bulldog2
    [Write-up]BSides-Vancouver
    Write-up-Bob_v1.0.1
    Genymotion设置代理至BurpSuite和Charles
    PE之RVA转FOA
    django的序列化
  • 原文地址:https://www.cnblogs.com/chenbin7/p/2499728.html
Copyright © 2011-2022 走看看