Android学习笔记(12)————利用SQLiteOpenHelper来管理SQLite数据库

本文介绍了如何使用SQLiteOpenHelper管理Android应用的SQLite数据库,包括构造函数参数解析、onCreate和onUpgrade方法的使用,以及getWritableDatabase和getReadableDatabase的区别,并提供了一个结合ListView的实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/********************************************************************************************
 * 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)方法会被自动添加。

/*
 * @author:conowen
 * 
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值