转载自 利用SQLiteOpenHelper来管理SQLite数据库

http://blog.csdn.net/conowen/article/details/7306545

 
 
 
/********************************************************************************************
 * author:conowen@大钟                                                                                                                          
 * E-mail:conowen@hotmail.com                                                                                                             
 * 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)方法会被自动添加。

  1. /*
  2. * @author:conowen
  3. * @date:12.2.29
  4. */
  5. package com.conowen.sqlite;
  6. import android.content.Context;
  7. import android.database.sqlite.SQLiteDatabase;
  8. import android.database.sqlite.SQLiteDatabase.CursorFactory;
  9. import android.database.sqlite.SQLiteOpenHelper;
  10. public class DbHelper extends SQLiteOpenHelper{
  11. public DbHelper(Context context, String name, CursorFactory factory,
  12. int version) {
  13. super(context, name, factory, version);
  14. // TODO Auto-generated constructor stub
  15. }
  16. @Override
  17. public void onCreate(SQLiteDatabase db) {
  18. // TODO Auto-generated method stub
  19. }
  20. @Override
  21. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  22. // TODO Auto-generated method stub
  23. }
  24. }

方法详解

  1. public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
Since: 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 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()方法。

  1. public DbHelper(Context context, String name, CursorFactory factory,
  2. int version) {
  3. super(context, name, factory, version);
  4. // TODO Auto-generated constructor stub
  5. }

以上是SQLiteOpenHelper 的构造函数,当数据库不存在时,就会创建数据库,然后打开数据库(过程已经被封装起来了),再调用onCreate (SQLiteDatabase db)方法来执行创建表之类的操作。当数据库存在时,SQLiteOpenHelper 就不会调用onCreate (SQLiteDatabase db)方法了,它会检测版本号,若传入的版本号高于当前的,就会执行onUpgrade()方法来更新数据库和版本号。

3、SQLiteOpenHelper的两个主要方法

3.1、onCreate方法

  1. public abstract void onCreate (SQLiteDatabase db)<span class="normal"></span>
Since: 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.
  1. //这样就创建一个一个table
  2. @Override
  3. public void onCreate(SQLiteDatabase db) {
  4. // TODO Auto-generated method stub
  5. String sql = "CREATE  TABLE table_name(_id INTEGER PRIMARY KEY , filename VARCHAR, data TEXT)";
  6. db.execSQL(sql);
  7. }

3.2、onUpgrade方法

  1. public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)
Since: 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.

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例子(也可以当做通讯录小工具)

效果图如下

  1. /*主activity
  2. * @author:conowen
  3. * @date:12.3.1
  4. */
  5. package com.conowen.sqlite;
  6. import android.app.Activity;
  7. import android.content.ContentValues;
  8. import android.database.Cursor;
  9. import android.database.sqlite.SQLiteDatabase;
  10. import android.os.Bundle;
  11. import android.view.View;
  12. import android.view.View.OnClickListener;
  13. import android.widget.Button;
  14. import android.widget.EditText;
  15. import android.widget.ListAdapter;
  16. import android.widget.ListView;
  17. import android.widget.SimpleCursorAdapter;
  18. import android.widget.Toast;
  19. public class SqliteActivity extends Activity {
  20. SQLiteDatabase sqldb;
  21. public String DB_NAME = "sql.db";
  22. public String DB_TABLE = "num";
  23. public int DB_VERSION = 1;
  24. final DbHelper helper = new DbHelper(this, DB_NAME, null, DB_VERSION);
  25. // DbHelper类在DbHelper.java文件里面创建的
  26. /** Called when the activity is first created. */
  27. @Override
  28. public void onCreate(Bundle savedInstanceState) {
  29. super.onCreate(savedInstanceState);
  30. setContentView(R.layout.main);
  31. sqldb = helper.getWritableDatabase();
  32. // 通过helper的getWritableDatabase()得到SQLiteOpenHelper所创建的数据库
  33. Button insert = (Button) findViewById(R.id.insert);
  34. Button delete = (Button) findViewById(R.id.delete);
  35. Button update = (Button) findViewById(R.id.update);
  36. Button query = (Button) findViewById(R.id.query);
  37. final ContentValues cv = new ContentValues();
  38. // ContentValues是“添加”和“更新”两个操作的数据载体
  39. updatelistview();// 更新listview
  40. // 添加insert
  41. insert.setOnClickListener(new OnClickListener() {
  42. @Override
  43. public void onClick(View v) {
  44. // TODO Auto-generated method stub
  45. EditText et_name = (EditText) findViewById(R.id.name);
  46. EditText et_phone = (EditText) findViewById(R.id.phone);
  47. cv.put("name", et_name.getText().toString());
  48. cv.put("phone", et_phone.getText().toString());
  49. // name和phone为列名
  50. long res = sqldb.insert("addressbook", null, cv);// 插入数据
  51. if (res == -1) {
  52. Toast.makeText(SqliteActivity.this, "添加失败",
  53. Toast.LENGTH_SHORT).show();
  54. } else {
  55. Toast.makeText(SqliteActivity.this, "添加成功",
  56. Toast.LENGTH_SHORT).show();
  57. }
  58. updatelistview();// 更新listview
  59. }
  60. });
  61. // 删除
  62. delete.setOnClickListener(new OnClickListener() {
  63. @Override
  64. public void onClick(View v) {
  65. // TODO Auto-generated method stub
  66. int res = sqldb.delete("addressbook", "name='大钟'", null);
  67. // 删除列名name,行名为“大钟”的,这一行的所有数据,null表示这一行的所有数据
  68. // 若第二个参数为null,则删除表中所有列对应的所有行的数据,也就是把table清空了。
  69. // name='大钟',大钟要单引号的
  70. // 返回值为删除的行数
  71. if (res == 0) {
  72. Toast.makeText(SqliteActivity.this, "删除失败",
  73. Toast.LENGTH_SHORT).show();
  74. } else {
  75. Toast.makeText(SqliteActivity.this, "成删除了" + res + "行的数据",
  76. Toast.LENGTH_SHORT).show();
  77. }
  78. updatelistview();// 更新listview
  79. }
  80. });
  81. // 更改
  82. update.setOnClickListener(new OnClickListener() {
  83. @Override
  84. public void onClick(View v) {
  85. // TODO Auto-generated method stub
  86. cv.put("name", "大钟");
  87. cv.put("phone", "1361234567");
  88. int res = sqldb.update("addressbook", cv, "name='张三'", null);
  89. // 把name=张三所在行的数据,全部更新为ContentValues所对应的数据
  90. // 返回时为成功更新的行数
  91. Toast.makeText(SqliteActivity.this, "成功更新了" + res + "行的数据",
  92. Toast.LENGTH_SHORT).show();
  93. updatelistview();// 更新listview
  94. }
  95. });
  96. // 查询
  97. query.setOnClickListener(new OnClickListener() {
  98. @Override
  99. public void onClick(View v) {
  100. // TODO Auto-generated method stub
  101. Cursor cr = sqldb.query("addressbook", null, null, null, null,
  102. null, null);
  103. // 返回名为addressbook的表的所有数据
  104. Toast.makeText(SqliteActivity.this,
  105. "一共有" + cr.getCount() + "条记录", Toast.LENGTH_SHORT)
  106. .show();
  107. updatelistview();// 更新listview
  108. }
  109. });
  110. }
  111. // 更新listview
  112. public void updatelistview() {
  113. ListView lv = (ListView) findViewById(R.id.lv);
  114. final Cursor cr = sqldb.query("addressbook", null, null, null, null,
  115. null, null);
  116. String[] ColumnNames = cr.getColumnNames();
  117. // ColumnNames为数据库的表的列名,getColumnNames()为得到指定table的所有列名
  118. ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.layout,
  119. cr, ColumnNames, new int[] { R.id.tv1, R.id.tv2, R.id.tv3 });
  120. // layout为listView的布局文件,包括三个TextView,用来显示三个列名所对应的值
  121. // ColumnNames为数据库的表的列名
  122. // 最后一个参数是int[]类型的,为view类型的id,用来显示ColumnNames列名所对应的值。view的类型为TextView
  123. lv.setAdapter(adapter);
  124. }
  125. }
  1. /*SQLiteOpenHelper类
  2. * @author:conowen
  3. * @date:12.3.1
  4. */
  5. package com.conowen.sqlite;
  6. import android.content.Context;
  7. import android.database.sqlite.SQLiteDatabase;
  8. import android.database.sqlite.SQLiteDatabase.CursorFactory;
  9. import android.database.sqlite.SQLiteOpenHelper;
  10. public class DbHelper extends SQLiteOpenHelper {
  11. public DbHelper(Context context, String name, CursorFactory factory,
  12. int version) {
  13. super(context, name, factory, version);
  14. // TODO Auto-generated constructor stub
  15. }
  16. @Override
  17. public void onCreate(SQLiteDatabase db) {
  18. // TODO Auto-generated method stub
  19. String sql = "CREATE  TABLE addressbook (_id INTEGER PRIMARY KEY , name VARCHAR, phone VARCHAR)";
  20. db.execSQL(sql);
  21. }
  22. @Override
  23. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  24. // TODO Auto-generated method stub
  25. }
  26. }

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <EditText
  7. android:id="@+id/name"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content" />
  10. <EditText
  11. android:id="@+id/phone"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content" />
  14. <LinearLayout
  15. android:id="@+id/linearLayout1"
  16. android:layout_width="fill_parent"
  17. android:layout_height="wrap_content" >
  18. <Button
  19. android:id="@+id/insert"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:text="增加" />
  23. <Button
  24. android:id="@+id/delete"
  25. android:layout_width="wrap_content"
  26. android:layout_height="wrap_content"
  27. android:text="删除" />
  28. <Button
  29. android:id="@+id/update"
  30. android:layout_width="wrap_content"
  31. android:layout_height="wrap_content"
  32. android:text="更改" />
  33. <Button
  34. android:id="@+id/query"
  35. android:layout_width="wrap_content"
  36. android:layout_height="wrap_content"
  37. android:text="查询" />
  38. </LinearLayout>
  39. <ListView
  40. android:id="@+id/lv"
  41. android:layout_width="fill_parent"
  42. android:layout_height="wrap_content" >
  43. </ListView>
  44. </LinearLayout>

ListView的布局文件layout.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="horizontal" >
  6. <TextView
  7. android:id="@+id/tv1"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:textSize="20sp"
  11. android:width="50px" />
  12. <TextView
  13. android:id="@+id/tv2"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:textSize="20sp"
  17. android:width="50px"
  18. />
  19. <TextView
  20. android:id="@+id/tv3"
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"
  23. android:textSize="20sp"
  24. android:width="150px" />
  25. </LinearLayout>

利用SQLiteOpenHelper来管理SQLite数据库 (转)的更多相关文章

  1. 在VB中利用Nuget包使用SQLite数据库和Linq to SQLite

    上午解决了在C#中利用Nuget包使用SQLite数据库和Linq to SQLite,但是最后生成的是C#的cs类文件,对于我这熟悉VB而对C#白痴的来说怎么能行呢? 于是下午接着研究,既然生成的是 ...

  2. 在Android中查看和管理sqlite数据库

    在Android中可以使用Eclipse插件DDMS来查看,也可以使用Android工具包中的adb工具来查看.android项目中的sqlite数据库位于/data/data/项目包/databas ...

  3. 在C#中利用Nuget包使用SQLite数据库和Linq to SQLite

    本来是学习在VB中使用SQLite数据库和Linq to SQLite,结果先学习到了在C#中使用SQLite数据库和Linq to SQLite的方法,写出来与大家共同学习.(不知道算不算不务正业) ...

  4. Android 查看和管理sqlite数据库

    在Android中可以使用Eclipse插件DDMS来查看,也可以使用Android工具包中的adb工具来查看.android项目中的sqlite数据库位于/data/data/项目包/databas ...

  5. Android学习记录:SQLite数据库、res中raw的文件调用

    SQLite数据库是一种轻量级的关系型数据库. 在android中保存数据或调用数据库可以利用SQLite. android中提供了几个类来管理SQLite数据库 SQLiteDatabass类用来对 ...

  6. SQLite数据库增删改查

    一:SQLite数据库简介: SQLite是一种轻量级的关系型数据库,官网:http://www.sqlite.org/. SQLite数据库文件存在于移动设备的一下目录中:data->data ...

  7. android中与SQLite数据库相关的类

    为什么要在应用程序中使用数据库?数据库最主要的用途就是作为数据的存储容器,另外,由于可以很方便的将应用程序中的数据结构(比如C语言中的结构体)转化成数据库的表,这样我们就可以通过操作数据库来替代写一堆 ...

  8. SQLite数据库学习小结——Frameworks层实现

    3. SQLite的Frameworks层实现 3.1 Frameworks层架构 Android系统方便应用使用,在Frameworks层中封装了一套Content框架,之所以叫Content框架而 ...

  9. SQLite数据库下载、安装和学习

    SQLite 是一个开源的嵌入式关系数据库,实现自包容.零配置.支持事务的SQL数据库引擎. 其特点是高度便携.使用方便.结构紧凑.高效.可靠.与其他数据库管理系统不同,SQLite 的安装和运行非常 ...

随机推荐

  1. C语言时间函数

    #include "time.h" #include "stdio.h" #include "stdlib.h" int main() { ...

  2. SQL Server 2005 发布 订阅 (配置实例[图])(转载)

    2.1          发布&订阅 1.       测 试环境: Item 发布机 A 订阅机 B OS Windows 2003 Server Windows 2003 Server S ...

  3. C/C++中的getline函数总结:

    来自:http://www.cnblogs.com/xFreedom/archive/2011/05/16/2048037.html C/C++中的getline函数总结 getline函数是一个比较 ...

  4. 无法卸载windows组件?提示zClientm.exe

    在卸载windows的组件: wmp, outlook, msessager等,提示: 找不到zClientm.exe 文件? 原来, zclientm.exe是windows的游戏组件依赖的文件, ...

  5. 模板插件aTpl.js新增功能

    摘要: aTpl.js是一款模板插件,该插件支持ie5+,chrome等浏览器以及移动端浏览器,支持for和if语法,以及表达式.最近对aTpl.js模板插件增加了新的功能,支持字符串模板,同时增加了 ...

  6. iOS工程如何支持64-bit(转)

    苹果在2014年10月20号发布了一条消息:从明年的二月一号开始,提交到App Store的应用必须支持64-bit.详细消息地址为:https://developer.apple.com/news/ ...

  7. zstu.4189: 逻辑运算(构建 && 前缀表达式入门)

    4189: 逻辑运算 Time Limit: 1 Sec  Memory Limit: 128 MB Submit: 274  Solved: 42 Description 还记得大学里学过的模电么, ...

  8. js矩阵菜单或3D立体预览图片效果

    js矩阵菜单或3D立体预览图片效果 下载地址: http://files.cnblogs.com/elves/js%E7%9F%A9%E9%98%B5%E8%8F%9C%E5%8D%95%E6%88% ...

  9. 改变edittext边框颜色

    转载自:点击打开链接 第一步:为了更好的比较,准备两个一模一样的EditText(当Activity启动时,焦点会在第一个EditText上,如果你不希望这样只需要写一个高度和宽带为0的EditTex ...

  10. mysql启动报错(mac)

    $mysql ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) ...