因為"建立",所以它有onCreate的方法。
因為"管理版本",所以它有onUpgrade/onDowngrade的方法。
此外它也提供了open/close方法來開啟與關閉資料庫
但我們並不直接呼叫onCreate與open方法,而是呼叫getReadableDatabase()或者getWritableDatabase()後,系統會執行open()方法。
public abstract class
SQLiteOpenHelper extends Object (SQLiteOpenHelper extend 自 Object)
java.lang.Object
↳ android.database.sqlite.SQLiteOpenHelper (要使用SQLiteOpenHelper這個Class需要import android.database.sqlite.SQLiteOpenHelper)
Class Overview
A helper class to manage database creation and version management.
You create a subclass implementing
This class makes it easy for onCreate(SQLiteDatabase)
, onUpgrade(SQLiteDatabase, int, int)
and optionally onOpen(SQLiteDatabase)
, and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. Transactions are used to make sure the database is always in a sensible state.ContentProvider
implementations to defer opening and upgrading the database until first use, to avoid blocking application startup with long-running database upgrades.helper class用於管理資料庫的建立與版本控制
SQLiteOpenHelper也有助於ContentProvider的使用效率
Summary
Public Constructors | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Create a helper object to create, open, and/or manage a database.
| |||||||||||
Create a helper object to create, open, and/or manage a database.
|
Public Methods | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Close any open database object.
| |||||||||||
Return the name of the SQLite database being opened, as given to the constructor.
| |||||||||||
Create and/or open a database.
| |||||||||||
Create and/or open a database that will be used for reading and writing.
| |||||||||||
Called when the database connection is being configured, to enable features such as write-ahead logging or foreign key support.
| |||||||||||
Called when the database is created for the first time.
| |||||||||||
Called when the database needs to be downgraded.
| |||||||||||
Called when the database has been opened.
| |||||||||||
Called when the database needs to be upgraded.
| |||||||||||
Enables or disables the use of write-ahead logging for the database.
|
Public Constructors
public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
Added in API level 1
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
getWritableDatabase()
or getReadableDatabase()
is called.Parameters
context | to use to open or create the database |
---|---|
name | of the database file, or null for an in-memory database |
factory | to use for creating cursor objects, or null for the default |
version | number of the database (starting at 1); if the database is older, onUpgrade(SQLiteDatabase, int, int) will be used to upgrade the database; if the database is newer, onDowngrade(SQLiteDatabase, int, int) will be used to downgrade the database |
public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version,DatabaseErrorHandler errorHandler)
Added in API level 11
Create a helper object to create, open, and/or manage a database. The database is not actually created or opened until one of
getWritableDatabase()
orgetReadableDatabase()
is called.
Accepts input param: a concrete instance of
DatabaseErrorHandler
to be used to handle corruption when sqlite reports database corruption.Parameters
context | to use to open or create the database |
---|---|
name | of the database file, or null for an in-memory database |
factory | to use for creating cursor objects, or null for the default |
version | number of the database (starting at 1); if the database is older, onUpgrade(SQLiteDatabase, int, int) will be used to upgrade the database; if the database is newer, onDowngrade(SQLiteDatabase, int, int) will be used to downgrade the database |
errorHandler | the DatabaseErrorHandler to be used when sqlite reports database corruption, or null to use the default error handler. |
Public Methods
public String getDatabaseName ()
Added in API level 14
Return the name of the SQLite database being opened, as given to the constructor.
public SQLiteDatabase getReadableDatabase ()
Added in API level 1
Create and/or open a database. This will be the same object returned by
getWritableDatabase()
unless some problem, such as a full disk, requires the database to be opened read-only. In that case, a read-only database object will be returned. If the problem is fixed, a future call to getWritableDatabase()
may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future.
Like
getWritableDatabase()
, this method may take a long time to return, so you should not call it from the application main thread, including fromContentProvider.onCreate()
.Returns
- a database object valid until
getWritableDatabase()
orclose()
is called.
Throws
SQLiteException | if the database cannot be opened |
---|
public SQLiteDatabase getWritableDatabase ()
Added in API level 1
Create and/or open a database that will be used for reading and writing. The first time this is called, the database will be opened and
onCreate(SQLiteDatabase)
, onUpgrade(SQLiteDatabase, int, int)
and/or onOpen(SQLiteDatabase)
will be called.
Once opened successfully, the database is cached, so you can call this method every time you need to write to the database. (Make sure to call
close()
when you no longer need the database.) Errors such as bad permissions or a full disk may cause this method to fail, but future attempts may succeed if the problem is fixed.
Database upgrade may take a long time, you should not call this method from the application main thread, including from
ContentProvider.onCreate()
.Returns
- a read/write database object valid until
close()
is called
Throws
SQLiteException | if the database cannot be opened for writing |
---|
public void onConfigure (SQLiteDatabase db)
Added in API level 16
Called when the database connection is being configured, to enable features such as write-ahead logging or foreign key support.
This method is called before
onCreate(SQLiteDatabase)
, onUpgrade(SQLiteDatabase, int, int)
, onDowngrade(SQLiteDatabase, int, int)
, oronOpen(SQLiteDatabase)
are called. It should not modify the database except to configure the database connection as required.
This method should only call methods that configure the parameters of the database connection, such as
enableWriteAheadLogging()
setForeignKeyConstraintsEnabled(boolean)
, setLocale(Locale)
, setMaximumSize(long)
, or executing PRAGMA statements.Parameters
db | The database. |
---|
public abstract void onCreate (SQLiteDatabase db)
Added in API level 1
Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.
Parameters
db | The database. |
---|
public void onDowngrade (SQLiteDatabase db, int oldVersion, int newVersion)
Added in API level 11
Called when the database needs to be downgraded. This is strictly similar to
onUpgrade(SQLiteDatabase, int, int)
method, but is called whenever current version is newer than requested one. However, this method is not abstract, so it is not mandatory for a customer to implement it. If not overridden, default implementation will reject downgrade and throws SQLiteException
This method executes within a transaction. If an exception is thrown, all changes will automatically be rolled back.
Parameters
db | The database. |
---|---|
oldVersion | The old database version. |
newVersion | The new database version. |
public void onOpen (SQLiteDatabase db)
Added in API level 1
Called when the database has been opened. The implementation should check
isReadOnly()
before updating the database.
This method is called after the database connection has been configured and after the database schema has been created, upgraded or downgraded as necessary. If the database connection must be configured in some way before the schema is created, upgraded, or downgraded, do it in
onConfigure(SQLiteDatabase)
instead.Parameters
db | The database. |
---|
public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)
Added in API level 1
Called when the database needs to be upgraded. The implementation should use this method to drop tables, add tables, or do anything else it needs to upgrade to the new schema version.
The SQLite ALTER TABLE documentation can be found here. If you add new columns you can use ALTER TABLE to insert them into a live table. If you rename or remove columns you can use ALTER TABLE to rename the old table, then create the new table and then populate the new table with the contents of the old table.
This method executes within a transaction. If an exception is thrown, all changes will automatically be rolled back.
Parameters
db | The database. |
---|---|
oldVersion | The old database version. |
newVersion | The new database version. |
public void setWriteAheadLoggingEnabled (boolean enabled)
Added in API level 16
Enables or disables the use of write-ahead logging for the database. Write-ahead logging cannot be used with read-only databases so the value of this flag is ignored if the database is opened read-only.
Parameters
enabled | True if write-ahead logging should be enabled, false if it should be disabled. |
---|
See Also
private static final String DATABASE_NAME = "exam.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_TABLE = "notes";
private static final String DATABASE_CREATE =
"create table notes("
+"_id INTEGER PRIMARY KEY,"
+"note TEXT,"
+"created INTEGER,"
+"modified INTEGER"
+");";
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}
}
參考資料: http://developer.android.com/intl/zh-tw/reference/android/database/sqlite/SQLiteOpenHelper.html
沒有留言:
張貼留言