/********************************************************************************************
* author:conowen@大钟
* E-mail:[email protected]
* http://blog.csdn.net/conowen
* 注:本文为原创,仅作为学习交流使用,转载请标明作者及出处。
********************************************************************************************/
1、SQLiteOpenHelper介绍
通过上篇博文,http://blog.csdn.net/conowen/article/details/7276417,了解了SQLite数据库的相关操作方法,但是一般在实际开发中,为了更加方便地管理、维护、升级数据库,需要通过继承SQLiteOpenHelper类来管理SQLite数据库。
关于SQLiteOpenHelper的官方说明如下:
A helper class to manage database creation and version management.
You create a subclass implementing onCreate(SQLiteDatabase)
,onUpgrade(SQLiteDatabase, int, int)
and optionallyonOpen(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.
This class makes it easy for ContentProvider
implementations to defer opening and upgrading the database until first use, to avoid blocking application startup with long-running database upgrades.
For an example, see the NotePadProvider class in the NotePad sample application, in thesamples/ directory of the SDK.
简单翻译:SQLiteOpenHelper可以创建数据库,和管理数据库的版本。
在继承SQLiteOpenHelper的类(extends
SQLiteOpenHelper
)里面,通过
复写onCreate(SQLiteDatabase)
,onUpgrade(SQLiteDatabase, int, int)
和onOpen(SQLiteDatabase)
(可选)来操作数据库。
2、SQLiteOpenHelper()的具体用法
创建一个新的class如下所示,onCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)方法会被自动添加。
-
-
-
-
-
- package com.conowen.sqlite;
-
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- import android.database.sqlite.SQLiteOpenHelper;
-
- public class DbHelper extends SQLiteOpenHelper{
-
- public DbHelper(Context context, String name, CursorFactory factory,
- int version) {
- super(context, name, factory, version);
-
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
-
-
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-
-
- }
-
- }
方法详解
- public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
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 ofgetWritableDatabase()
orgetReadableDatabase()
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 |
参数简述:
name————表示数据库文件名(不包括文件路径),SQLiteOpenHelper类会根据这个文件名来创建数据库文件。
version————表示数据库的版本号。如果当前传入的数据库版本号比上一次创建的版本高,SQLiteOpenHelper就会调用onUpgrade()方法。
- public DbHelper(Context context, String name, CursorFactory factory,
- int version) {
- super(context, name, factory, version);
-
- }
以上是SQLiteOpenHelper 的构造函数,当数据库不存在时,
就会创建数据库,然后打开数据库(过程已经被封装起来了),再调用onCreate (SQLiteDatabase db)方法来执行创建表之类的操作。当数据库存在时,SQLiteOpenHelper 就不会调用onCreate (SQLiteDatabase db)方法了,它会检测版本号,若传入的版本号高于当前的,就会执行onUpgrade()方法来更新数据库和版本号。
3、SQLiteOpenHelper的两个主要方法
3.1、onCreate方法
- public abstract void onCreate (SQLiteDatabase db)<span class="normal"></span>
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
-
- @Override
- public void onCreate(SQLiteDatabase db) {
-
-
- String sql = "CREATE TABLE table_name(_id INTEGER PRIMARY KEY , filename VARCHAR, data TEXT)";
- db.execSQL(sql);
-
- }
3.2、onUpgrade方法
- public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)
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.
Parameters
db |
The database. |
oldVersion |
The old database version. |
newVersion |
The new database version. |
更新数据库,包括删除表,添加表等各种操作。若版本是第一版,也就是刚刚建立数据库,onUpgrade()方法里面就不用写东西,因为第一版数据库何来更新之说,以后发布的版本,数据库更新的话,可以在onUpgrade()方法添加各种更新的操作。
4、注意事项
创建完SQLiteOpenHelper 类之后,在主activity里面就可以通过SQLiteOpenHelper.getWritableDatabase()或者getReadableDatabase()方法来获取在SQLiteOpenHelper 类里面创建的数据库实例。(也就是说只有调用这两种方法才真正地实例化数据库)
getWritableDatabase() 方法————以读写方式打开数据库,如果数据库所在磁盘空间满了,而使用的又是getWritableDatabase() 方法就会出错。
因为此时数据库就只能读而不能写,
getReadableDatabase()方法————则是先以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,但是当打开失败后会继续尝试以只读
方式打开数据库。而不会报错
=========================================================================================================
下面演示一个以SQLite的数据库为adapter的listview例子(也可以当做通讯录小工具)
效果图如下
-
-
-
-
- package com.conowen.sqlite;
-
- import android.app.Activity;
- import android.content.ContentValues;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ListAdapter;
- import android.widget.ListView;
- import android.widget.SimpleCursorAdapter;
- import android.widget.Toast;
-
- public class SqliteActivity extends Activity {
- SQLiteDatabase sqldb;
- public String DB_NAME = "sql.db";
- public String DB_TABLE = "num";
- public int DB_VERSION = 1;
- final DbHelper helper = new DbHelper(this, DB_NAME, null, DB_VERSION);
-
-
-
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- sqldb = helper.getWritableDatabase();
-
- Button insert = (Button) findViewById(R.id.insert);
- Button delete = (Button) findViewById(R.id.delete);
- Button update = (Button) findViewById(R.id.update);
- Button query = (Button) findViewById(R.id.query);
- final ContentValues cv = new ContentValues();
-
- updatelistview();
-
- insert.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View v) {
-
- EditText et_name = (EditText) findViewById(R.id.name);
- EditText et_phone = (EditText) findViewById(R.id.phone);
- cv.put("name", et_name.getText().toString());
- cv.put("phone", et_phone.getText().toString());
-
- long res = sqldb.insert("addressbook", null, cv);
- if (res == -1) {
- Toast.makeText(SqliteActivity.this, "添加失败",
- Toast.LENGTH_SHORT).show();
- } else {
- Toast.makeText(SqliteActivity.this, "添加成功",
- Toast.LENGTH_SHORT).show();
- }
- updatelistview();
- }
- });
-
- delete.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View v) {
-
- int res = sqldb.delete("addressbook", "name='大钟'", null);
-
-
-
-
- if (res == 0) {
- Toast.makeText(SqliteActivity.this, "删除失败",
- Toast.LENGTH_SHORT).show();
- } else {
- Toast.makeText(SqliteActivity.this, "成删除了" + res + "行的数据",
- Toast.LENGTH_SHORT).show();
- }
- updatelistview();
-
- }
- });
-
- update.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View v) {
-
- cv.put("name", "大钟");
- cv.put("phone", "1361234567");
- int res = sqldb.update("addressbook", cv, "name='张三'", null);
-
-
- Toast.makeText(SqliteActivity.this, "成功更新了" + res + "行的数据",
- Toast.LENGTH_SHORT).show();
-
- updatelistview();
- }
- });
-
- query.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View v) {
-
- Cursor cr = sqldb.query("addressbook", null, null, null, null,
- null, null);
-
- Toast.makeText(SqliteActivity.this,
- "一共有" + cr.getCount() + "条记录", Toast.LENGTH_SHORT)
- .show();
-
- updatelistview();
- }
- });
-
- }
-
-
- public void updatelistview() {
- ListView lv = (ListView) findViewById(R.id.lv);
-
- final Cursor cr = sqldb.query("addressbook", null, null, null, null,
- null, null);
- String[] ColumnNames = cr.getColumnNames();
-
-
- ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.layout,
- cr, ColumnNames, new int[] { R.id.tv1, R.id.tv2, R.id.tv3 });
-
-
-
- lv.setAdapter(adapter);
- }
- }
-
-
-
-
- package com.conowen.sqlite;
-
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- import android.database.sqlite.SQLiteOpenHelper;
-
- public class DbHelper extends SQLiteOpenHelper {
-
- public DbHelper(Context context, String name, CursorFactory factory,
- int version) {
- super(context, name, factory, version);
-
-
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
-
-
- String sql = "CREATE TABLE addressbook (_id INTEGER PRIMARY KEY , name VARCHAR, phone VARCHAR)";
- db.execSQL(sql);
-
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-
-
- }
-
- }
main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <EditText
- android:id="@+id/name"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
-
- <EditText
- android:id="@+id/phone"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
-
- <LinearLayout
- android:id="@+id/linearLayout1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" >
-
- <Button
- android:id="@+id/insert"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="增加" />
-
- <Button
- android:id="@+id/delete"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="删除" />
-
- <Button
- android:id="@+id/update"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="更改" />
-
- <Button
- android:id="@+id/query"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="查询" />
- </LinearLayout>
-
- <ListView
- android:id="@+id/lv"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" >
- </ListView>
-
- </LinearLayout>
ListView的布局文件layout.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="horizontal" >
- <TextView
- android:id="@+id/tv1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="20sp"
- android:width="50px" />
- <TextView
- android:id="@+id/tv2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="20sp"
- android:width="50px"
- />
- <TextView
- android:id="@+id/tv3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="20sp"
- android:width="150px" />
-
- </LinearLayout>