Android中SQLite 使用方法详解


当前第2页 返回上一页

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

public synchronized SQLiteDatabase getReadableDatabase() { 
  if (mDatabase != null && mDatabase.isOpen()) { 
    // 如果发现mDatabase不为空并且已经打开则直接返回 
    return mDatabase; 
  } 
 
  if (mIsInitializing) { 
    // 如果正在初始化则抛出异常 
    throw new IllegalStateException("getReadableDatabase called recursively"); 
  } 
 
  // 开始实例化数据库mDatabase 
 
  try { 
    // 注意这里是调用了getWritableDatabase()方法 
    return getWritableDatabase(); 
  } catch (SQLiteException e) { 
    if (mName == null) 
      throw e; // Can't open a temp database read-only! 
    Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e); 
  } 
 
  // 如果无法以可读写模式打开数据库 则以只读方式打开 
 
  SQLiteDatabase db = null; 
  try { 
    mIsInitializing = true; 
    String path = mContext.getDatabasePath(mName).getPath();// 获取数据库路径 
    // 以只读方式打开数据库 
    db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY); 
    if (db.getVersion() != mNewVersion) { 
      throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to " 
          + mNewVersion + ": " + path); 
    } 
 
    onOpen(db); 
    Log.w(TAG, "Opened " + mName + " in read-only mode"); 
    mDatabase = db;// 为mDatabase指定新打开的数据库 
    return mDatabase;// 返回打开的数据库 
  } finally { 
    mIsInitializing = false; 
    if (db != null && db != mDatabase) 
      db.close(); 
  } 
} 

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

public synchronized SQLiteDatabase getWritableDatabase() { 
  if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) { 
    // 如果mDatabase不为空已打开并且不是只读模式 则返回该实例 
    return mDatabase; 
  } 
 
  if (mIsInitializing) { 
    throw new IllegalStateException("getWritableDatabase called recursively"); 
  } 
 
  // If we have a read-only database open, someone could be using it 
  // (though they shouldn't), which would cause a lock to be held on 
  // the file, and our attempts to open the database read-write would 
  // fail waiting for the file lock. To prevent that, we acquire the 
  // lock on the read-only database, which shuts out other users. 
 
  boolean success = false; 
  SQLiteDatabase db = null; 
  // 如果mDatabase不为空则加锁 阻止其他的操作 
  if (mDatabase != null) 
    mDatabase.lock(); 
  try { 
    mIsInitializing = true; 
    if (mName == null) { 
      db = SQLiteDatabase.create(null); 
    } else { 
      // 打开或创建数据库 
      db = mContext.openOrCreateDatabase(mName, 0, mFactory); 
    } 
    // 获取数据库版本(如果刚创建的数据库,版本为0) 
    int version = db.getVersion(); 
    // 比较版本(我们代码中的版本mNewVersion为1) 
    if (version != mNewVersion) { 
      db.beginTransaction();// 开始事务 
      try { 
        if (version == 0) { 
          // 执行我们的onCreate方法 
          onCreate(db); 
        } else { 
          // 如果我们应用升级了mNewVersion为2,而原版本为1则执行onUpgrade方法 
          onUpgrade(db, version, mNewVersion); 
        } 
        db.setVersion(mNewVersion);// 设置最新版本 
        db.setTransactionSuccessful();// 设置事务成功 
      } finally { 
        db.endTransaction();// 结束事务 
      } 
    } 
 
    onOpen(db); 
    success = true; 
    return db;// 返回可读写模式的数据库实例 
  } finally { 
    mIsInitializing = false; 
    if (success) { 
      // 打开成功 
      if (mDatabase != null) { 
        // 如果mDatabase有值则先关闭 
        try { 
          mDatabase.close(); 
        } catch (Exception e) { 
        } 
        mDatabase.unlock();// 解锁 
      } 
      mDatabase = db;// 赋值给mDatabase 
    } else { 
      // 打开失败的情况:解锁、关闭 
      if (mDatabase != null) 
        mDatabase.unlock(); 
      if (db != null) 
        db.close(); 
    } 
  } 
} 

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

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

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

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent"> 
  <Button 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="add" 
    android:onClick="add"/> 
  <Button 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="update" 
    android:onClick="update"/> 
  <Button 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="delete" 
    android:onClick="delete"/> 
  <Button 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="query" 
    android:onClick="query"/> 
  <Button 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="queryTheCursor" 
    android:onClick="queryTheCursor"/> 
  <ListView 
    android:id="@+id/listView" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"/> 
</LinearLayout> 
package com.scott.db; 
 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
 
import android.app.Activity; 
import android.database.Cursor; 
import android.database.CursorWrapper; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.SimpleCursorAdapter; 
 
 
public class MainActivity extends Activity { 
   
  private DBManager mgr; 
  private ListView listView; 
   
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    listView = (ListView) findViewById(R.id.listView); 
    //初始化DBManager 
    mgr = new DBManager(this); 
  } 
   
  @Override 
  protected void onDestroy() { 
    super.onDestroy(); 
    //应用的最后一个Activity关闭时应释放DB 
    mgr.closeDB(); 
  } 
   
  public void add(View view) { 
    ArrayList<Person> persons = new ArrayList<Person>(); 
     
    Person person1 = new Person("Ella", 22, "lively girl"); 
    Person person2 = new Person("Jenny", 22, "beautiful girl"); 
    Person person3 = new Person("Jessica", 23, "sexy girl"); 
    Person person4 = new Person("Kelly", 23, "hot baby"); 
    Person person5 = new Person("Jane", 25, "a pretty woman"); 
     
    persons.add(person1); 
    persons.add(person2); 
    persons.add(person3); 
    persons.add(person4); 
    persons.add(person5); 
     
    mgr.add(persons); 
  } 
   
  public void update(View view) { 
    Person person = new Person(); 
    person.name = "Jane"; 
    person.age = 30; 
    mgr.updateAge(person); 
  } 
   
  public void delete(View view) { 
    Person person = new Person(); 
    person.age = 30; 
    mgr.deleteOldPerson(person); 
  } 
   
  public void query(View view) { 
    List<Person> persons = mgr.query(); 
    ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>(); 
    for (Person person : persons) { 
      HashMap<String, String> map = new HashMap<String, String>(); 
      map.put("name", person.name); 
      map.put("info", person.age + " years old, " + person.info); 
      list.add(map); 
    } 
    SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, 
          new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2}); 
    listView.setAdapter(adapter); 
  } 
   
  public void queryTheCursor(View view) { 
    Cursor c = mgr.queryTheCursor(); 
    startManagingCursor(c); //托付给activity根据自己的生命周期去管理Cursor的生命周期 
    CursorWrapper cursorWrapper = new CursorWrapper(c) { 
      @Override 
      public String getString(int columnIndex) { 
        //将简介前加上年龄 
        if (getColumnName(columnIndex).equals("info")) { 
          int age = getInt(getColumnIndex("age")); 
          return age + " years old, " + super.getString(columnIndex); 
        } 
        return super.getString(columnIndex); 
      } 
    }; 
    //确保查询结果中有"_id"列 
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2,  
        cursorWrapper, new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2}); 
    ListView listView = (ListView) findViewById(R.id.listView); 
    listView.setAdapter(adapter); 
  } 
} 

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

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

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

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

CursorWrapper cursorWrapper = new CursorWrapper(c) { 
  @Override 
  public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException { 
    if (columnName.equals("_id")) { 
      return super.getColumnIndex("id"); 
    } 
    return super.getColumnIndexOrThrow(columnName); 
  } 
}; 

如果试图从CursorWrapper里获取“_id”对应的列索引,我们就返回查询结果里“id”对应的列索引即可。
最后我们来看一下结果如何:


感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


标签:SQLite

返回前面的内容

相关阅读 >>

android开发实现的导出数据库到excel表格功能【附源码下载】

navicat for mysql 16怎么注册?navicat16全系列最新破解教程(附注册机)

c#操作Sqlite数据库方法小结(创建,连接,插入,查询,删除等)

使用css连接数据库的方式

Sqlite expert pro5.0如何安装可视化数据库管理软件激活教程

navicat premium操作mysql数据库(执行sql语句)

python web框架之django框架model基础详解

c#操作Sqlite方法实例详解

python的消息队列包snakemq使用初探

ios开发中使用fmdb来使程序连接Sqlite数据库

更多相关阅读请进入《Sqlite》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...