转载自 利用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. ewebeditor编辑器ASP/ASPX/PHP/JSP版本漏洞利用总结及解决方法

    这个编辑器按脚本分主要有4个版本,ASP/ASPX/PHP/JSP 每个版本都有可以利用的漏洞.判断网站是否使用了eWebEditor查看程序源代码,看看源码中是否存在类似”ewebeditor.as ...

  2. Memcache的部署和使用(转)

    一.memcache简介 Memcache是danga.com的一个项目,最早是为 LiveJournal 服务的,目前全世界不少人使用这个缓存项目来构建自己大负载的网站,来分担数据库的压力. Mem ...

  3. 批量删除wordpress垃圾评论留言

    wordpress博客的存在,垃圾评论注定会找上门来.大家还可以用Akismet.Bad Behavior.Spam Karma等一些其他的插件或者直接用程序写个验证码函数对留言进行验证来过滤 垃圾评 ...

  4. 教你如何---构建良好的windows程序(初学者必看)

    一使用菜单栏和工具栏 1.菜单栏和工具栏有什么作用和优点: 通过菜单栏把应用程序的功能进行分组,能够方便用户查找和使用,下图所示的菜单栏包含的每一项都是顶层菜单项,顶层菜单项下的选项称为”子菜单”或” ...

  5. TCPIP三次握手详情

    TCP正常建立和关闭的状态变化 TCP连接的建立可以简单的称为三次握手,而连接的中止则可以叫做 四次握手. 建立连接 在TCP/IP协议中,TCP协议提供可靠的连接服务,采用三次握手建立一个连接. 第 ...

  6. unity3d iPhone文件目录介绍

    原地址:http://cl314413.blog.163.com/blog/static/190507976201210259126559/ 如何查看iPhone文件存放目录?首先需要越狱,越狱后打开 ...

  7. PHP无限极分类实现

    简单版的PHP生成无限极分类代码.其中包括了数据库设计.以及输出分类HTML代码. SQL代码 CREATE TABLE `district` ( `id` int(10) unsigned NOT ...

  8. 暑假热身 D. 条形码设计

    校ACM队准备筹划向学校批请一个专用机房.但是为了防止它变成公用机房,FL建议采用刷卡进入的办法,她设计了一种条形码,每人都对应一个.这种大小为2*n的条形码由以下三种元素构成:1*2.2*1.2*2 ...

  9. bellman ford优先队列优化简介模板

    #include<iostream>#include<cstdio>#include<utility>#include<queue>#include&l ...

  10. pro git 使用积累

    http://www.zhihu.com/question/20070065 git相关问题的收集 Git 是 Linux 之父 Linus Trovalds,为管理 Linux 内核代码而建立的,被 ...