Android数据存储---SQLite
来源:互联网 发布:淘宝客怎么转换淘口令 编辑:程序博客网 时间:2024/04/29 19:08
SQLite是一款轻量级数据库,支持大部分SQL语句。
下面我们来看看如何使用:
1.写一个工具类继承SQLiteOpenHelper,建数据库,建person表
import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class DBOpenHelper extends SQLiteOpenHelper { // 定义工具类, 继承SQLiteOpenHelperpublic DBOpenHelper(Context context) {// 创建对象的时候, 需要传入上下文环境super(context, "itcast.db", null, 4);/* * 由于父类没有无参构造函数, 必须显式调用有参的构造函数 * 参数1: 上下文环境, 用来确定数据库文件存储的目录 * 参数2: 数据库文件的名字 * 参数3: 生成游标的工厂, 填null就是使用默认的 * 参数4: 数据库的版本, 从1开始,只能从低版本更新到高版本 */}@Overridepublic void onCreate(SQLiteDatabase db) {System.out.println("onCreate");db.execSQL("CREATE TABLE person(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20))");// 执行SQL语句, 创建表}//数据库版本更新时调用此方法@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {System.out.println("onUpgrade");db.execSQL("ALTER TABLE person ADD balance INTEGER");}}
2.对Person对象进行增删改查
import java.util.ArrayList;import java.util.List;import cn.itcast.sqlite.domain.Person;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;public class PersonDao {private DBOpenHelper helper;public PersonDao(Context context) {helper = new DBOpenHelper(context);}public void insert(Person p) {SQLiteDatabase db = helper.getWritableDatabase(); // 获取数据库连接(可写的)ContentValues values = new ContentValues();// 类似于Map的容器, 键是String, 用来存放列名, 值是Object, 用来存要插入的数据values.put("name", p.getName());// 某些情况下, 程序会接收一个ContentValues参数, 这时用这种方式存储比较方便values.put("balance", p.getBalance());/* * 参数1:表名 * 参数2:用于指定空值字段的名称 * 参数3:插入的参数,null 表示用来在想插入一条除了主键全部为空的记录时使用 * 返回:插入记录的id */long id = db.insert("person", null, values);System.out.println("插入的记录的id是: " + id);db.close();}public void delete(int id) {SQLiteDatabase db = helper.getWritableDatabase();int rows = db.delete("person", "id=?", new String[] { id + "" });System.out.println("删除了" + rows + "行");db.close();}public void update(Person p) {SQLiteDatabase db = helper.getWritableDatabase();ContentValues values = new ContentValues();values.put("name", p.getName());values.put("balance", p.getBalance());int rows = db.update("person", values, "id=?", new String[] { p.getId() + "" });System.out.println("更新了" + rows + "行");db.close();}//query onepublic Person query(int id) {SQLiteDatabase db = helper.getReadableDatabase();// 获取数据库连接(可读的)Cursor c = db.query("person", new String[] { "name", "balance" }, "id=?", new String[] { id + "" }, null, null, null);Person p = null;if (c.moveToNext()) {// 判断游标是否包含下一条记录, 如果包含将游标向后移动一位String name = c.getString(c.getColumnIndex("name"));// 获取"name"字段的索引, 然后根据索引获取数据int balance = c.getInt(1);// 获取1号索引上的数据p = new Person(id, name, balance);}c.close();db.close();return p;}//查询所有public List<Person> queryAll() {SQLiteDatabase db = helper.getReadableDatabase();Cursor c = db.query("person", null, null, null, null, null, null);List<Person> persons = new ArrayList<Person>();while (c.moveToNext()) {Person p = new Person(c.getInt(0), c.getString(1), c.getInt(2));persons.add(p);}c.close();db.close();return persons;}//此方法是在ListView设置SimpleCursorAdapter适配器时调用public Cursor queryAllCursor() {SQLiteDatabase db = helper.getReadableDatabase(); /* * 使用Cursor相关的Adapter时需要一个自增的列,且名字必需为 _id */Cursor c = db.query("person", new String[] { "id _id", "name", "balance" }, null, null, null, null, null);return c;}//查询有多少记录public int queryCount() {SQLiteDatabase db = helper.getReadableDatabase();Cursor c = db.query("person", new String[]{ "COUNT(*)" }, null, null, null, null, null);c.moveToNext();int count = c.getInt(0);c.close();db.close();return count;}//分页public List<Person> queryPage(int pageNum, int capacity) {String offset = (pageNum - 1) * capacity + "";// 偏移量String len = capacity + "";// 个数SQLiteDatabase db = helper.getReadableDatabase();Cursor c = db.query("person", null, null, null, null, null, null, offset + "," + len);List<Person> persons = new ArrayList<Person>();while (c.moveToNext()) {Person p = new Person(c.getInt(0), c.getString(1), c.getInt(2));persons.add(p);}c.close();db.close();return persons;}//使用事物提交public void remit(int from, int to, int amount) {SQLiteDatabase db = helper.getWritableDatabase();try {db.beginTransaction();// 开始事务db.execSQL("UPDATE person SET balance=balance-? WHERE id=?", new Object[] { amount, from });db.execSQL("UPDATE person SET balance=balance+? WHERE id=?", new Object[] { amount, to });db.setTransactionSuccessful();// 设置成功点, 在事务结束时, 成功点之前的操作会被提交} finally {db.endTransaction();// 结束事务, 将成功点之前的操作提交db.close();}}}
3.写一个Test类,测试方法
import java.util.List;import cn.itcast.sqlite.domain.Person;import android.database.Cursor;import android.test.AndroidTestCase;public class DBTest extends AndroidTestCase {public void testCreateDatabase() {DBOpenHelper helper = new DBOpenHelper(getContext());helper.getWritableDatabase();/* * 获取可写的数据连接 * 数据库文件不存在时, 会创建数据库文件, 并且执行onCreate()方法 * 数据库文件存在, 并且版本没有改变时, 不执行任何方法 * 数据库文件存在, 版本提升, 执行onUpgrade()方法 */}public void testInsert() {PersonDao dao = new PersonDao(getContext());dao.insert(new Person("xxx", 9999));}public void testDelete() {PersonDao dao = new PersonDao(getContext());dao.delete(106);}public void testUpdate() {PersonDao dao = new PersonDao(getContext());dao.update(new Person(2, "李四", 10000));dao.update(new Person(3, "王五", 10000));}public void testQuery() {PersonDao dao = new PersonDao(getContext());System.out.println(dao.query(5));}public void testQueryAll() {PersonDao dao = new PersonDao(getContext());List<Person> persons = dao.queryAll();for (Person p : persons)System.out.println(p);}public void testQueryCount() {PersonDao dao = new PersonDao(getContext());System.out.println(dao.queryCount());}public void testQueryPage() {PersonDao dao = new PersonDao(getContext());List<Person> persons = dao.queryPage(2, 10);for (Person p : persons)System.out.println(p);}public void testRemit() {PersonDao dao = new PersonDao(getContext());dao.remit(3, 2, 1000);}public void testQueryAllCursor(){PersonDao dao = new PersonDao(getContext());Cursor c=dao.queryAllCursor();while(c.moveToNext()){System.out.println(c.getString(c.getColumnIndex("name")));}}}
- android数据存储--SQLite
- Android数据存储---SQLite
- Android数据存储-SQLite
- android-数据存储sqlite
- Android---数据存储SQLite
- Android 数据存储----SQLite
- android SQLite 数据存储
- Android SQLite数据存储
- 【Android】数据存储之SQLite
- android使用sqlite存储数据
- android-数据存储-SQLite数据库
- android数据存储之SQLite
- Android数据存储之SQLite
- Android数据存储之SQLite
- android数据存储-06-SQLite
- Android数据存储之SQLite
- Android之SQLite 数据存储
- android-SQLite数据库存储数据
- 【Visual C++】关于无法打开包括文件:“StdAfx.h”或者意外结尾的错误解决方案
- Big Endian与Little Endian区别
- APUE读书笔记(3.0) ——第三章 文件I/O
- 链表基本操作的实现
- 在网站制作中随时可用的10个 HTML5 代码片段
- Android数据存储---SQLite
- nagiosQL访问时报错PHP message: PHP Deprecated: preg_replace(): The /e modifier is deprecated, use preg_re
- gcc头文件库文件搜索路径问题
- 漫画:人资部和技术人员都是如何看你的简历的
- ffmpeg 编码器AVCodecContext 的配置参数
- RAII
- ios播放系统自带音效以及震动
- IOS中类和对象还有,nil/Nil/NULL的区别及小结
- mysql的myisam存储引擎特性(五)