上一篇文章 SQLite实用武器库(4)附加数据库(Attach DB)介绍了SQLite层面如何使用附加数据库。本文简单介绍在Android APP开发中如何使用。本文Android源代码基于Android6.0。
Attach/Detach DB操作是通过SQL语句实现,所以还是通过SQLiteDatabase.execSQL()实现。
/**
* Execute a single SQL statement that is NOT a SELECT
* or any other SQL statement that returns data.
* <p>
* It has no means to return any data (such as the number of affected rows).
* Instead, you're encouraged to use {@link #insert(String, String, ContentValues)},
* {@link #update(String, ContentValues, String, String[])}, et al, when possible.
* </p>
* <p>
* When using {@link #enableWriteAheadLogging()}, journal_mode is
* automatically managed by this class. So, do not set journal_mode
* using "PRAGMA journal_mode'<value>" statement if your app is using
* {@link #enableWriteAheadLogging()}
* </p>
*
* @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
* not supported.
* @throws SQLException if the SQL string is invalid
*/
public void execSQL(String sql) throws SQLException
具体使用例子:
db.execSQL(String.format("ATTACH DATABASE \'%s\' AS %s", path, name));
db.execSQL(String.format("DETACH DATABASE %s", name));
这里面有几个点需要注意:
1. 数据库路径问题
数据库文件路径(path)需要一个系统运行时SQLite能够识别的路径,而不能简单地传入db文件名(譬如 “mydatas.db”)。实现方法类似Android的SQLite数据库工具类SQLiteOpenHelper。我们看一下SQLiteOpenHelper的典型用法,构造方法中传入一个db文件名
/**
* Create a helper object to create, open, and/or manage a database.
* This method always returns very quickly. The database is not actually
* created or opened until one of {@link #getWritableDatabase} or